").addClass(a.oClasses.sPaging+b)[0];
var h=a.aanFeatures;d||c.fnInit(a,b,e);h.p||(b.id=a.sTableId+"_paginate",a.aoDrawCallback.push({fn:function(f){if(d){var g=f._iDisplayStart,k=f._iDisplayLength,m=f.fnRecordsDisplay(),n=-1===k;g=n?0:Math.ceil(g/k);k=n?1:Math.ceil(m/k);m=c(g,k);var p;n=0;for(p=h.p.length;n
h&&
(d=0)):"first"==b?d=0:"previous"==b?(d=0<=e?d-e:0,0>d&&(d=0)):"next"==b?d+e",{id:a.aanFeatures.r?null:a.sTableId+"_processing","class":a.oClasses.sProcessing}).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0]}function V(a,b){a.oFeatures.bProcessing&&l(a.aanFeatures.r).css("display",b?"block":"none");
F(a,null,"processing",[a,b])}function Mb(a){var b=l(a.nTable),c=a.oScroll;if(""===c.sX&&""===c.sY)return a.nTable;var d=c.sX,e=c.sY,h=a.oClasses,f=b.children("caption"),g=f.length?f[0]._captionSide:null,k=l(b[0].cloneNode(!1)),m=l(b[0].cloneNode(!1)),n=b.children("tfoot");n.length||(n=null);k=l("",{"class":h.sScrollWrapper}).append(l("
",{"class":h.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:d?d?K(d):null:"100%"}).append(l("
",{"class":h.sScrollHeadInner}).css({"box-sizing":"content-box",
width:c.sXInner||"100%"}).append(k.removeAttr("id").css("margin-left",0).append("top"===g?f:null).append(b.children("thead"))))).append(l("
",{"class":h.sScrollBody}).css({position:"relative",overflow:"auto",width:d?K(d):null}).append(b));n&&k.append(l("
",{"class":h.sScrollFoot}).css({overflow:"hidden",border:0,width:d?d?K(d):null:"100%"}).append(l("
",{"class":h.sScrollFootInner}).append(m.removeAttr("id").css("margin-left",0).append("bottom"===g?f:null).append(b.children("tfoot")))));
b=k.children();var p=b[0];h=b[1];var t=n?b[2]:null;if(d)l(h).on("scroll.DT",function(v){v=this.scrollLeft;p.scrollLeft=v;n&&(t.scrollLeft=v)});l(h).css("max-height",e);c.bCollapse||l(h).css("height",e);a.nScrollHead=p;a.nScrollBody=h;a.nScrollFoot=t;a.aoDrawCallback.push({fn:Ha,sName:"scrolling"});return k[0]}function Ha(a){var b=a.oScroll,c=b.sX,d=b.sXInner,e=b.sY;b=b.iBarWidth;var h=l(a.nScrollHead),f=h[0].style,g=h.children("div"),k=g[0].style,m=g.children("table");g=a.nScrollBody;var n=l(g),p=
g.style,t=l(a.nScrollFoot).children("div"),v=t.children("table"),x=l(a.nTHead),w=l(a.nTable),r=w[0],C=r.style,G=a.nTFoot?l(a.nTFoot):null,aa=a.oBrowser,L=aa.bScrollOversize;U(a.aoColumns,"nTh");var O=[],I=[],H=[],ea=[],Y,Ca=function(D){D=D.style;D.paddingTop="0";D.paddingBottom="0";D.borderTopWidth="0";D.borderBottomWidth="0";D.height=0};var fa=g.scrollHeight>g.clientHeight;if(a.scrollBarVis!==fa&&a.scrollBarVis!==q)a.scrollBarVis=fa,ta(a);else{a.scrollBarVis=fa;w.children("thead, tfoot").remove();
if(G){var ba=G.clone().prependTo(w);var la=G.find("tr");ba=ba.find("tr")}var mb=x.clone().prependTo(w);x=x.find("tr");fa=mb.find("tr");mb.find("th, td").removeAttr("tabindex");c||(p.width="100%",h[0].style.width="100%");l.each(Na(a,mb),function(D,W){Y=ua(a,D);W.style.width=a.aoColumns[Y].sWidth});G&&ca(function(D){D.style.width=""},ba);h=w.outerWidth();""===c?(C.width="100%",L&&(w.find("tbody").height()>g.offsetHeight||"scroll"==n.css("overflow-y"))&&(C.width=K(w.outerWidth()-b)),h=w.outerWidth()):
""!==d&&(C.width=K(d),h=w.outerWidth());ca(Ca,fa);ca(function(D){var W=z.getComputedStyle?z.getComputedStyle(D).width:K(l(D).width());H.push(D.innerHTML);O.push(W)},fa);ca(function(D,W){D.style.width=O[W]},x);l(fa).height(0);G&&(ca(Ca,ba),ca(function(D){ea.push(D.innerHTML);I.push(K(l(D).css("width")))},ba),ca(function(D,W){D.style.width=I[W]},la),l(ba).height(0));ca(function(D,W){D.innerHTML='
'+H[W]+"
";D.childNodes[0].style.height="0";D.childNodes[0].style.overflow=
"hidden";D.style.width=O[W]},fa);G&&ca(function(D,W){D.innerHTML='
'+ea[W]+"
";D.childNodes[0].style.height="0";D.childNodes[0].style.overflow="hidden";D.style.width=I[W]},ba);Math.round(w.outerWidth())
g.offsetHeight||"scroll"==n.css("overflow-y")?h+b:h,L&&(g.scrollHeight>g.offsetHeight||"scroll"==n.css("overflow-y"))&&(C.width=K(la-b)),""!==c&&""===d||da(a,1,"Possible column misalignment",6)):la="100%";p.width=K(la);f.width=K(la);
G&&(a.nScrollFoot.style.width=K(la));!e&&L&&(p.height=K(r.offsetHeight+b));c=w.outerWidth();m[0].style.width=K(c);k.width=K(c);d=w.height()>g.clientHeight||"scroll"==n.css("overflow-y");e="padding"+(aa.bScrollbarLeft?"Left":"Right");k[e]=d?b+"px":"0px";G&&(v[0].style.width=K(c),t[0].style.width=K(c),t[0].style[e]=d?b+"px":"0px");w.children("colgroup").insertBefore(w.children("thead"));n.trigger("scroll");!a.bSorted&&!a.bFiltered||a._drawHold||(g.scrollTop=0)}}function ca(a,b,c){for(var d=0,e=0,h=
b.length,f,g;e").appendTo(g.find("tbody"));g.find("thead, tfoot").remove();g.append(l(a.nTHead).clone()).append(l(a.nTFoot).clone());g.find("tfoot th, tfoot td").css("width","");m=Na(a,g.find("thead")[0]);for(v=0;v").css({width:w.sWidthOrig,margin:0,padding:0,border:0,height:1}));if(a.aoData.length)for(v=0;v").css(h||e?{position:"absolute",top:0,left:0,height:1,right:0,overflow:"hidden"}:{}).append(g).appendTo(p);h&&f?g.width(f):h?(g.css("width","auto"),g.removeAttr("width"),g.width()").css("width",K(a)).appendTo(b||A.body);b=a[0].offsetWidth;a.remove();return b}function $b(a,b){var c=
ac(a,b);if(0>c)return null;var d=a.aoData[c];return d.nTr?d.anCells[b]:l("").html(T(a,c,b,"display"))[0]}function ac(a,b){for(var c,d=-1,e=-1,h=0,f=a.aoData.length;hd&&(d=c.length,e=h);return e}function K(a){return null===a?"0px":"number"==typeof a?0>a?"0px":a+"px":a.match(/\d$/)?a+"px":a}function pa(a){var b=[],c=a.aoColumns;var d=a.aaSortingFixed;var e=l.isPlainObject(d);var h=[];var f=function(n){n.length&&
!Array.isArray(n[0])?h.push(n):l.merge(h,n)};Array.isArray(d)&&f(d);e&&d.pre&&f(d.pre);f(a.aaSorting);e&&d.post&&f(d.post);for(a=0;aG?1:0;if(0!==C)return"asc"===r.dir?C:-C}C=c[n];G=c[p];return CG?1:0}):f.sort(function(n,p){var t,v=g.length,x=e[n]._aSortData,w=e[p]._aSortData;for(t=0;tG?1:0})}a.bSorted=!0}function cc(a){var b=a.aoColumns,c=pa(a);a=a.oLanguage.oAria;for(var d=0,e=b.length;d/g,"");var k=h.nTh;k.removeAttribute("aria-sort");h.bSortable&&(0e?e+1:3))}e=
0;for(h=d.length;ee?e+1:3))}a.aLastSort=d}function bc(a,b){var c=a.aoColumns[b],d=u.ext.order[c.sSortDataType],e;d&&(e=d.call(a.oInstance,a,b,va(a,b)));for(var h,f=u.ext.type.order[c.sType+"-pre"],g=0,k=a.aoData.length;g=e.length?[0,m[1]]:m)}));b.search!==q&&l.extend(a.oPreviousSearch,Wb(b.search));if(b.columns){f=0;for(d=b.columns.length;f=c&&(b=c-d);b-=b%d;if(-1===d||0>b)b=0;a._iDisplayStart=b}function gb(a,b){a=a.renderer;var c=u.ext.renderer[b];return l.isPlainObject(a)&&a[b]?c[a[b]]||c._:"string"===typeof a?c[a]||c._:c._}function Q(a){return a.oFeatures.bServerSide?
"ssp":a.ajax||a.sAjaxSource?"ajax":"dom"}function Da(a,b){var c=ec.numbers_length,d=Math.floor(c/2);b<=c?a=ra(0,b):a<=d?(a=ra(0,c-2),a.push("ellipsis"),a.push(b-1)):(a>=b-1-d?a=ra(b-(c-2),b):(a=ra(a-d+2,a+d-1),a.push("ellipsis"),a.push(b-1)),a.splice(0,0,"ellipsis"),a.splice(0,0,0));a.DT_el="span";return a}function Xa(a){l.each({num:function(b){return Ua(b,a)},"num-fmt":function(b){return Ua(b,a,rb)},"html-num":function(b){return Ua(b,a,Va)},"html-num-fmt":function(b){return Ua(b,a,Va,rb)}},function(b,
c){M.type.order[b+a+"-pre"]=c;b.match(/^html\-/)&&(M.type.search[b+a]=M.type.search.html)})}function fc(a){return function(){var b=[Ta(this[u.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return u.ext.internal[a].apply(this,b)}}var u=function(a,b){if(this instanceof u)return l(a).DataTable(b);b=a;this.$=function(f,g){return this.api(!0).$(f,g)};this._=function(f,g){return this.api(!0).rows(f,g).data()};this.api=function(f){return f?new B(Ta(this[M.iApiIndex])):new B(this)};this.fnAddData=
function(f,g){var k=this.api(!0);f=Array.isArray(f)&&(Array.isArray(f[0])||l.isPlainObject(f[0]))?k.rows.add(f):k.row.add(f);(g===q||g)&&k.draw();return f.flatten().toArray()};this.fnAdjustColumnSizing=function(f){var g=this.api(!0).columns.adjust(),k=g.settings()[0],m=k.oScroll;f===q||f?g.draw(!1):(""!==m.sX||""!==m.sY)&&Ha(k)};this.fnClearTable=function(f){var g=this.api(!0).clear();(f===q||f)&&g.draw()};this.fnClose=function(f){this.api(!0).row(f).child.hide()};this.fnDeleteRow=function(f,g,k){var m=
this.api(!0);f=m.rows(f);var n=f.settings()[0],p=n.aoData[f[0][0]];f.remove();g&&g.call(this,n,p);(k===q||k)&&m.draw();return p};this.fnDestroy=function(f){this.api(!0).destroy(f)};this.fnDraw=function(f){this.api(!0).draw(f)};this.fnFilter=function(f,g,k,m,n,p){n=this.api(!0);null===g||g===q?n.search(f,k,m,p):n.column(g).search(f,k,m,p);n.draw()};this.fnGetData=function(f,g){var k=this.api(!0);if(f!==q){var m=f.nodeName?f.nodeName.toLowerCase():"";return g!==q||"td"==m||"th"==m?k.cell(f,g).data():
k.row(f).data()||null}return k.data().toArray()};this.fnGetNodes=function(f){var g=this.api(!0);return f!==q?g.row(f).node():g.rows().nodes().flatten().toArray()};this.fnGetPosition=function(f){var g=this.api(!0),k=f.nodeName.toUpperCase();return"TR"==k?g.row(f).index():"TD"==k||"TH"==k?(f=g.cell(f).index(),[f.row,f.columnVisible,f.column]):null};this.fnIsOpen=function(f){return this.api(!0).row(f).child.isShown()};this.fnOpen=function(f,g,k){return this.api(!0).row(f).child(g,k).show().child()[0]};
this.fnPageChange=function(f,g){f=this.api(!0).page(f);(g===q||g)&&f.draw(!1)};this.fnSetColumnVis=function(f,g,k){f=this.api(!0).column(f).visible(g);(k===q||k)&&f.columns.adjust().draw()};this.fnSettings=function(){return Ta(this[M.iApiIndex])};this.fnSort=function(f){this.api(!0).order(f).draw()};this.fnSortListener=function(f,g,k){this.api(!0).order.listener(f,g,k)};this.fnUpdate=function(f,g,k,m,n){var p=this.api(!0);k===q||null===k?p.row(g).data(f):p.cell(g,k).data(f);(n===q||n)&&p.columns.adjust();
(m===q||m)&&p.draw();return 0};this.fnVersionCheck=M.fnVersionCheck;var c=this,d=b===q,e=this.length;d&&(b={});this.oApi=this.internal=M.internal;for(var h in u.ext.internal)h&&(this[h]=fc(h));this.each(function(){var f={},g=1").appendTo(t));r.nTHead=H[0];var ea=t.children("tbody");0===ea.length&&(ea=l("").insertAfter(H));r.nTBody=ea[0];H=t.children("tfoot");0===H.length&&0").appendTo(t));0===H.length||0===H.children().length?t.addClass(C.sNoFooter):0/g,uc=/^\d{2,4}[\.\/\-]\d{1,2}[\.\/\-]\d{1,2}([T ]{1}\d{1,2}[:\.]\d{2}([\.:]\d{2})?)?$/,vc=/(\/|\.|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\|\$|\^|\-)/g,rb=/['\u00A0,$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfkɃΞ]/gi,Z=function(a){return a&&!0!==a&&"-"!==a?!1:!0},hc=
function(a){var b=parseInt(a,10);return!isNaN(b)&&isFinite(a)?b:null},ic=function(a,b){sb[b]||(sb[b]=new RegExp(jb(b),"g"));return"string"===typeof a&&"."!==b?a.replace(/\./g,"").replace(sb[b],"."):a},tb=function(a,b,c){var d="string"===typeof a;if(Z(a))return!0;b&&d&&(a=ic(a,b));c&&d&&(a=a.replace(rb,""));return!isNaN(parseFloat(a))&&isFinite(a)},jc=function(a,b,c){return Z(a)?!0:Z(a)||"string"===typeof a?tb(a.replace(Va,""),b,c)?!0:null:null},U=function(a,b,c){var d=[],e=0,h=a.length;if(c!==q)for(;e<
h;e++)a[e]&&a[e][b]&&d.push(a[e][b][c]);else for(;ea.length)){var b=a.slice().sort();for(var c=b[0],d=1,e=b.length;d<
e;d++){if(b[d]===c){b=!1;break a}c=b[d]}}b=!0}if(b)return a.slice();b=[];e=a.length;var h,f=0;d=0;a:for(;d")[0],sc=Qa.textContent!==q,tc=/<.*?>/g,hb=u.util.throttle,nc=[],N=Array.prototype,wc=function(a){var b,c=u.settings,d=l.map(c,function(h,f){return h.nTable});if(a){if(a.nTable&&a.oApi)return[a];if(a.nodeName&&"table"===a.nodeName.toLowerCase()){var e=
l.inArray(a,d);return-1!==e?[c[e]]:null}if(a&&"function"===typeof a.settings)return a.settings().toArray();"string"===typeof a?b=l(a):a instanceof l&&(b=a)}else return[];if(b)return b.map(function(h){e=l.inArray(this,d);return-1!==e?c[e]:null}).toArray()};var B=function(a,b){if(!(this instanceof B))return new B(a,b);var c=[],d=function(f){(f=wc(f))&&c.push.apply(c,f)};if(Array.isArray(a))for(var e=0,h=a.length;ea?new B(b[a],this[a]):null},filter:function(a){var b=[];if(N.filter)b=N.filter.call(this,a,this);else for(var c=0,d=this.length;c").addClass(g),l("td",k).addClass(g).html(f)[0].colSpan=oa(a),e.push(k[0]))};h(c,d);b._details&&b._details.detach();b._details=l(e);b._detailsShow&&b._details.insertAfter(b.nTr)},xb=function(a,b){var c=a.context;c.length&&(a=c[0].aoData[b!==q?b:a[0]])&&a._details&&(a._details.remove(),a._detailsShow=q,a._details=
q,l(a.nTr).removeClass("dt-hasChild"),qa(c[0]))},qc=function(a,b){var c=a.context;if(c.length&&a.length){var d=c[0].aoData[a[0]];d._details&&((d._detailsShow=b)?(d._details.insertAfter(d.nTr),l(d.nTr).addClass("dt-hasChild")):(d._details.detach(),l(d.nTr).removeClass("dt-hasChild")),F(c[0],null,"childRow",[b,a.row(a[0])]),zc(c[0]),qa(c[0]))}},zc=function(a){var b=new B(a),c=a.aoData;b.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");0g){var n=l.map(d,function(p,t){return p.bVisible?t:null});return[n[n.length+g]]}return[ua(a,g)];case "name":return l.map(e,function(p,t){return p===m[1]?t:null});default:return[]}if(f.nodeName&&f._DT_CellIndex)return[f._DT_CellIndex.column];g=l(h).filter(f).map(function(){return l.inArray(this,h)}).toArray();if(g.length||!f.nodeName)return g;g=l(f).closest("*[data-dt-column]");return g.length?[g.data("dt-column")]:[]},a,c)};y("columns()",function(a,b){a===q?a="":l.isPlainObject(a)&&(b=a,
a="");b=vb(b);var c=this.iterator("table",function(d){return Bc(d,a,b)},1);c.selector.cols=a;c.selector.opts=b;return c});J("columns().header()","column().header()",function(a,b){return this.iterator("column",function(c,d){return c.aoColumns[d].nTh},1)});J("columns().footer()","column().footer()",function(a,b){return this.iterator("column",function(c,d){return c.aoColumns[d].nTf},1)});J("columns().data()","column().data()",function(){return this.iterator("column-rows",rc,1)});J("columns().dataSrc()",
"column().dataSrc()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].mData},1)});J("columns().cache()","column().cache()",function(a){return this.iterator("column-rows",function(b,c,d,e,h){return Ea(b.aoData,h,"search"===a?"_aFilterData":"_aSortData",c)},1)});J("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(a,b,c,d,e){return Ea(a.aoData,e,"anCells",b)},1)});J("columns().visible()","column().visible()",function(a,b){var c=
this,d=this.iterator("column",function(e,h){if(a===q)return e.aoColumns[h].bVisible;var f=e.aoColumns,g=f[h],k=e.aoData,m;if(a!==q&&g.bVisible!==a){if(a){var n=l.inArray(!0,U(f,"bVisible"),h+1);f=0;for(m=k.length;fd;return!0};u.isDataTable=u.fnIsDataTable=function(a){var b=l(a).get(0),c=!1;if(a instanceof u.Api)return!0;l.each(u.settings,function(d,e){d=e.nScrollHead?l("table",e.nScrollHead)[0]:null;var h=e.nScrollFoot?l("table",e.nScrollFoot)[0]:null;if(e.nTable===b||d===b||h===b)c=!0});return c};u.tables=u.fnTables=function(a){var b=
!1;l.isPlainObject(a)&&(b=a.api,a=a.visible);var c=l.map(u.settings,function(d){if(!a||a&&l(d.nTable).is(":visible"))return d.nTable});return b?new B(c):c};u.camelToHungarian=P;y("$()",function(a,b){b=this.rows(b).nodes();b=l(b);return l([].concat(b.filter(a).toArray(),b.find(a).toArray()))});l.each(["on","one","off"],function(a,b){y(b+"()",function(){var c=Array.prototype.slice.call(arguments);c[0]=l.map(c[0].split(/\s/),function(e){return e.match(/\.dt\b/)?e:e+".dt"}).join(" ");var d=l(this.tables().nodes());
d[b].apply(d,c);return this})});y("clear()",function(){return this.iterator("table",function(a){Ka(a)})});y("settings()",function(){return new B(this.context,this.context)});y("init()",function(){var a=this.context;return a.length?a[0].oInit:null});y("data()",function(){return this.iterator("table",function(a){return U(a.aoData,"_aData")}).flatten()});y("destroy()",function(a){a=a||!1;return this.iterator("table",function(b){var c=b.nTableWrapper.parentNode,d=b.oClasses,e=b.nTable,h=b.nTBody,f=b.nTHead,
g=b.nTFoot,k=l(e);h=l(h);var m=l(b.nTableWrapper),n=l.map(b.aoData,function(t){return t.nTr}),p;b.bDestroying=!0;F(b,"aoDestroyCallback","destroy",[b]);a||(new B(b)).columns().visible(!0);m.off(".DT").find(":not(tbody *)").off(".DT");l(z).off(".DT-"+b.sInstance);e!=f.parentNode&&(k.children("thead").detach(),k.append(f));g&&e!=g.parentNode&&(k.children("tfoot").detach(),k.append(g));b.aaSorting=[];b.aaSortingFixed=[];Sa(b);l(n).removeClass(b.asStripeClasses.join(" "));l("th, td",f).removeClass(d.sSortable+
" "+d.sSortableAsc+" "+d.sSortableDesc+" "+d.sSortableNone);h.children().detach();h.append(n);f=a?"remove":"detach";k[f]();m[f]();!a&&c&&(c.insertBefore(e,b.nTableReinsertBefore),k.css("width",b.sDestroyWidth).removeClass(d.sTable),(p=b.asDestroyStripes.length)&&h.children().each(function(t){l(this).addClass(b.asDestroyStripes[t%p])}));c=l.inArray(b,u.settings);-1!==c&&u.settings.splice(c,1)})});l.each(["column","row","cell"],function(a,b){y(b+"s().every()",function(c){var d=this.selector.opts,e=
this;return this.iterator(b,function(h,f,g,k,m){c.call(e[b](f,"cell"===b?g:d,"cell"===b?d:q),f,g,k,m)})})});y("i18n()",function(a,b,c){var d=this.context[0];a=na(a)(d.oLanguage);a===q&&(a=b);c!==q&&l.isPlainObject(a)&&(a=a[c]!==q?a[c]:a._);return a.replace("%d",c)});u.version="1.11.4";u.settings=[];u.models={};u.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0,"return":!1};u.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",
src:null,idx:-1};u.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};u.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,
25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(a){return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,
fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(a){try{return JSON.parse((-1===a.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+a.sInstance+"_"+location.pathname))}catch(b){return{}}},fnStateLoadParams:null,fnStateLoaded:null,fnStateSaveCallback:function(a,b){try{(-1===a.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+a.sInstance+"_"+location.pathname,JSON.stringify(b))}catch(c){}},
fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",
sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:l.extend({},u.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",searchDelay:null,sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null,rowId:"DT_RowId"};E(u.defaults);u.defaults.column={aDataSort:null,
iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};E(u.defaults.column);u.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,
iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1,bBounding:!1,barWidth:0},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aIds:{},aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],
aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,searchDelay:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,jqXHR:null,json:q,oAjaxData:q,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,
bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==Q(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==Q(this)?1*this._iRecordsDisplay:this.aiDisplay.length},fnDisplayEnd:function(){var a=this._iDisplayLength,b=this._iDisplayStart,c=b+a,d=this.aiDisplay.length,e=this.oFeatures,h=
e.bPaginate;return e.bServerSide?!1===h||-1===a?b+d:Math.min(b+a,this._iRecordsDisplay):!h||c>d||-1===a?d:c},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{},rowIdFn:null,rowId:null};u.ext=M={buttons:{},classes:{},builder:"dt/dt-1.11.4",errMode:"alert",feature:[],search:[],selector:{cell:[],column:[],row:[]},internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:u.fnVersionCheck,
iApiIndex:0,oJUIClasses:{},sVersion:u.version};l.extend(M,{afnFiltering:M.search,aTypes:M.type.detect,ofnSearch:M.type.search,oSort:M.type.order,afnSortData:M.order,aoFeatures:M.feature,oApi:M.internal,oStdClasses:M.classes,oPagination:M.pager});l.extend(u.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",
sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_desc_disabled",sSortableDesc:"sorting_asc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",
sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});var ec=u.ext.pager;l.extend(ec,{simple:function(a,b){return["previous","next"]},full:function(a,b){return["first","previous","next","last"]},numbers:function(a,b){return[Da(a,b)]},simple_numbers:function(a,b){return["previous",Da(a,b),"next"]},
full_numbers:function(a,b){return["first","previous",Da(a,b),"next","last"]},first_last_numbers:function(a,b){return["first",Da(a,b),"last"]},_numbers:Da,numbers_length:7});l.extend(!0,u.ext.renderer,{pageButton:{_:function(a,b,c,d,e,h){var f=a.oClasses,g=a.oLanguage.oPaginate,k=a.oLanguage.oAria.paginate||{},m,n,p=0,t=function(x,w){var r,C=f.sPageButtonDisabled,G=function(I){Ra(a,I.data.action,!0)};var aa=0;for(r=w.length;aa").appendTo(x);
t(O,L)}else{m=null;n=L;O=a.iTabIndex;switch(L){case "ellipsis":x.append('… ');break;case "first":m=g.sFirst;0===e&&(O=-1,n+=" "+C);break;case "previous":m=g.sPrevious;0===e&&(O=-1,n+=" "+C);break;case "next":m=g.sNext;if(0===h||e===h-1)O=-1,n+=" "+C;break;case "last":m=g.sLast;if(0===h||e===h-1)O=-1,n+=" "+C;break;default:m=a.fnFormatNumber(L+1),n=e===L?f.sPageButtonActive:""}null!==m&&(O=l("",{"class":f.sPageButton+" "+n,"aria-controls":a.sTableId,"aria-label":k[L],
"data-dt-idx":p,tabindex:O,id:0===c&&"string"===typeof L?a.sTableId+"_"+L:null}).html(m).appendTo(x),ob(O,{action:L},G),p++)}}};try{var v=l(b).find(A.activeElement).data("dt-idx")}catch(x){}t(l(b).empty(),d);v!==q&&l(b).find("[data-dt-idx="+v+"]").trigger("focus")}}});l.extend(u.ext.type.detect,[function(a,b){b=b.oLanguage.sDecimal;return tb(a,b)?"num"+b:null},function(a,b){if(a&&!(a instanceof Date)&&!uc.test(a))return null;b=Date.parse(a);return null!==b&&!isNaN(b)||Z(a)?"date":null},function(a,
b){b=b.oLanguage.sDecimal;return tb(a,b,!0)?"num-fmt"+b:null},function(a,b){b=b.oLanguage.sDecimal;return jc(a,b)?"html-num"+b:null},function(a,b){b=b.oLanguage.sDecimal;return jc(a,b,!0)?"html-num-fmt"+b:null},function(a,b){return Z(a)||"string"===typeof a&&-1!==a.indexOf("<")?"html":null}]);l.extend(u.ext.type.search,{html:function(a){return Z(a)?a:"string"===typeof a?a.replace(gc," ").replace(Va,""):""},string:function(a){return Z(a)?a:"string"===typeof a?a.replace(gc," "):a}});var Ua=function(a,
b,c,d){if(0!==a&&(!a||"-"===a))return-Infinity;b&&(a=ic(a,b));a.replace&&(c&&(a=a.replace(c,"")),d&&(a=a.replace(d,"")));return 1*a};l.extend(M.type.order,{"date-pre":function(a){a=Date.parse(a);return isNaN(a)?-Infinity:a},"html-pre":function(a){return Z(a)?"":a.replace?a.replace(/<.*?>/g,"").toLowerCase():a+""},"string-pre":function(a){return Z(a)?"":"string"===typeof a?a.toLowerCase():a.toString?a.toString():""},"string-asc":function(a,b){return ab?1:0},"string-desc":function(a,b){return a<
b?1:a>b?-1:0}});Xa("");l.extend(!0,u.ext.renderer,{header:{_:function(a,b,c,d){l(a.nTable).on("order.dt.DT",function(e,h,f,g){a===h&&(e=c.idx,b.removeClass(d.sSortAsc+" "+d.sSortDesc).addClass("asc"==g[e]?d.sSortAsc:"desc"==g[e]?d.sSortDesc:c.sSortingClass))})},jqueryui:function(a,b,c,d){l(" ").addClass(d.sSortJUIWrapper).append(b.contents()).append(l("").addClass(d.sSortIcon+" "+c.sSortingClassJUI)).appendTo(b);l(a.nTable).on("order.dt.DT",function(e,h,f,g){a===h&&(e=c.idx,b.removeClass(d.sSortAsc+
" "+d.sSortDesc).addClass("asc"==g[e]?d.sSortAsc:"desc"==g[e]?d.sSortDesc:c.sSortingClass),b.find("span."+d.sSortIcon).removeClass(d.sSortJUIAsc+" "+d.sSortJUIDesc+" "+d.sSortJUI+" "+d.sSortJUIAscAllowed+" "+d.sSortJUIDescAllowed).addClass("asc"==g[e]?d.sSortJUIAsc:"desc"==g[e]?d.sSortJUIDesc:c.sSortingClassJUI))})}}});var yb=function(a){Array.isArray(a)&&(a=a.join(","));return"string"===typeof a?a.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""):a};u.render=
{number:function(a,b,c,d,e){return{display:function(h){if("number"!==typeof h&&"string"!==typeof h)return h;var f=0>h?"-":"",g=parseFloat(h);if(isNaN(g))return yb(h);g=g.toFixed(c);h=Math.abs(g);g=parseInt(h,10);h=c?b+(h-g).toFixed(c).substring(2):"";0===g&&0===parseFloat(h)&&(f="");return f+(d||"")+g.toString().replace(/\B(?=(\d{3})+(?!\d))/g,a)+h+(e||"")}}},text:function(){return{display:yb,filter:yb}}};l.extend(u.ext.internal,{_fnExternApiFunc:fc,_fnBuildAjax:Oa,_fnAjaxUpdate:Gb,_fnAjaxParameters:Pb,
_fnAjaxUpdateDraw:Qb,_fnAjaxDataSrc:Aa,_fnAddColumn:Ya,_fnColumnOptions:Ga,_fnAdjustColumnSizing:ta,_fnVisibleToColumnIndex:ua,_fnColumnIndexToVisible:va,_fnVisbleColumns:oa,_fnGetColumns:Ia,_fnColumnTypes:$a,_fnApplyColumnDefs:Db,_fnHungarianMap:E,_fnCamelToHungarian:P,_fnLanguageCompat:ma,_fnBrowserDetect:Bb,_fnAddData:ia,_fnAddTr:Ja,_fnNodeToDataIndex:function(a,b){return b._DT_RowIndex!==q?b._DT_RowIndex:null},_fnNodeToColumnIndex:function(a,b,c){return l.inArray(c,a.aoData[b].anCells)},_fnGetCellData:T,
_fnSetCellData:Eb,_fnSplitObjNotation:cb,_fnGetObjectDataFn:na,_fnSetObjectDataFn:ha,_fnGetDataMaster:db,_fnClearTable:Ka,_fnDeleteIndex:La,_fnInvalidate:wa,_fnGetRowElements:bb,_fnCreateTr:ab,_fnBuildHead:Fb,_fnDrawHead:ya,_fnDraw:ja,_fnReDraw:ka,_fnAddOptionsHtml:Ib,_fnDetectHeader:xa,_fnGetUniqueThs:Na,_fnFeatureHtmlFilter:Kb,_fnFilterComplete:za,_fnFilterCustom:Tb,_fnFilterColumn:Sb,_fnFilter:Rb,_fnFilterCreateSearch:ib,_fnEscapeRegex:jb,_fnFilterData:Ub,_fnFeatureHtmlInfo:Nb,_fnUpdateInfo:Xb,
_fnInfoMacros:Yb,_fnInitialise:Ba,_fnInitComplete:Pa,_fnLengthChange:kb,_fnFeatureHtmlLength:Jb,_fnFeatureHtmlPaginate:Ob,_fnPageChange:Ra,_fnFeatureHtmlProcessing:Lb,_fnProcessingDisplay:V,_fnFeatureHtmlTable:Mb,_fnScrollDraw:Ha,_fnApplyToChildren:ca,_fnCalculateColumnWidths:Za,_fnThrottle:hb,_fnConvertToWidth:Zb,_fnGetWidestNode:$b,_fnGetMaxLenString:ac,_fnStringToCss:K,_fnSortFlatten:pa,_fnSort:Hb,_fnSortAria:cc,_fnSortListener:nb,_fnSortAttachListener:fb,_fnSortingClasses:Sa,_fnSortData:bc,_fnSaveState:qa,
_fnLoadState:dc,_fnImplementState:pb,_fnSettingsFromNode:Ta,_fnLog:da,_fnMap:X,_fnBindAction:ob,_fnCallbackReg:R,_fnCallbackFire:F,_fnLengthOverflow:lb,_fnRenderer:gb,_fnDataSource:Q,_fnRowAttributes:eb,_fnExtend:qb,_fnCalculateEnd:function(){}});l.fn.dataTable=u;u.$=l;l.fn.dataTableSettings=u.settings;l.fn.dataTableExt=u.ext;l.fn.DataTable=function(a){return l(this).dataTable(a).api()};l.each(u,function(a,b){l.fn.DataTable[a]=b});return u});
/*!
DataTables styling integration
©2018 SpryMedia Ltd - datatables.net/license
*/
(function(c){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(a){return c(a,window,document)}):"object"===typeof exports?module.exports=function(a,b){a||(a=window);b&&b.fn.dataTable||(b=require("datatables.net")(a,b).$);return c(b,a,a.document)}:c(jQuery,window,document)})(function(c,a,b,d){return c.fn.dataTable});
var propath = "/c/cesavas/img/p/";
var imgpath="/c/cesavas";
var prosuf = "-r600.jpg";
var fampath = "/c/cesavas/img/c/";
var famsuf = "-r600.jpg";
var propagination = 1;
var procurrent = 0;
var contadortotal = 0;
var contadorposicion = 0;
var iszoom = 0;
var unidadesventa=["Minorista","Mayorista","Paquete3","Paquete4","Paquete5","Paquete6"];
var unidadesventashort=["Min","May","Paq3","Paq4","Paq5","Paq6"];
var unidadesventadefecto=-1;
var SUCURSAL1=0;
var SUCURSAL2=-1;
var MINIMOVENTA=0;
var MINIMOVENTADESBLOQUEO="kk";
var SALTOMENUCONUNO="1";
var OCULTARUNICAUNIDADVENTA="1";
var KFEA_TIPO="";
var KFEA_TIPO2="M_CATEGORIA";
var KFEA_COLOR="";
var appclient="cesavas";
var STOCKAGENTE="0";
var INICIOREFERENCIA="0";
var COBRARCARTERA="0";
var STOCKDANGER="-100000";
var STOCKWARNING="-100000";
/*dmentalsoft*/
//const { array } = require("prop-types");
const soundEffect = new Audio();
var online = 1;
var swreg; //service worker
var currentswversion = 0;
var kcontra = "";
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
alert("Error occured: " + errorMsg); //or any message
return false;
};
function imgonerror() {
$("img").on("error", function () {
$(this).attr("src", "broken.gif");
});
}
function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
function final_on() {
imgonerror();
}
function trimChar(string, charToRemove) {
while (string.charAt(0) == charToRemove) {
string = string.substring(1);
}
while (string.charAt(string.length - 1) == charToRemove) {
string = string.substring(0, string.length - 1);
}
return string;
}
function uuidv4() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
function uuidv4_date() {
thisdt = new Date();
kdt =
thisdt.getFullYear().toString().substring(2, 4) +
"" +
(thisdt.getMonth() + 1 < 10 ? "0" : "") +
(thisdt.getMonth() + 1) +
"" +
(thisdt.getDate() < 10 ? "0" : "") +
thisdt.getDate() +
"" +
(thisdt.getHours() < 10 ? "0" : "") +
thisdt.getHours() +
"-" +
(thisdt.getMinutes() < 10 ? "0" : "") +
thisdt.getMinutes() +
"" +
(thisdt.getSeconds() < 10 ? "0" : "") +
thisdt.getSeconds();
return (kdt + "-4xxx-yxxx-xxxxxxxxxxxx").replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
var drawpedidostimer = null;
function isEmpty(val) {
return val === undefined || val == null || val.length <= 0 ? true : false;
}
// For todays date;
Date.prototype.today = function () {
return (
(this.getDate() < 10 ? "0" : "") +
this.getDate() +
"/" +
(this.getMonth() + 1 < 10 ? "0" : "") +
(this.getMonth() + 1) +
"/" +
this.getFullYear()
);
};
// For the time now
Date.prototype.timeNow = function () {
return (
(this.getHours() < 10 ? "0" : "") +
this.getHours() +
":" +
(this.getMinutes() < 10 ? "0" : "") +
this.getMinutes() +
":" +
(this.getSeconds() < 10 ? "0" : "") +
this.getSeconds()
);
};
// For todays date;
Date.prototype.compressdt = function () {
return (
this.getFullYear() +
"" +
(this.getMonth() + 1 < 10 ? "0" : "") +
(this.getMonth() + 1) +
"" +
(this.getDate() < 10 ? "0" : "") +
this.getDate() +
"" +
(this.getHours() < 10 ? "0" : "") +
this.getHours() +
"" +
(this.getMinutes() < 10 ? "0" : "") +
this.getMinutes() +
"" +
(this.getSeconds() < 10 ? "0" : "") +
this.getSeconds()
);
};
$(".buscador").hover(
function () {
$("#navbarlogo").hide();
},
function () {
setTimeout(function () {
$("#navbarlogo").show();
}, 500);
}
);
//alert(($( ".kcol" ).width()-545)/2);
//$(".imgprocol").css("margin-left","96px");
var aproduct = null;
var afam = null;
var alb = null;
var albformat=null;
var adr = null;
var pref = null;
var cli = null;
var cartera = null;
var sts = null;
var tventas = null;
var ashowproducts = null;
var relacionadosh = 0;
var relacionadosch = 0;
var relacionadoscw = 0;
var cnf = null;
var kanchopro = 0;
var cuantoscorazones = 0;
var localpedido = {};
var localcli = -1;
var localag = -1;
var cliag = null;
var cliagstk = null;
var timeoutloadlotes = null;
var botoncobrarcartera=null;
function loadImagePro(kthis, idpro) {
if (kthis.attr("src") != kthis.attr("data-src")) {
kthis.attr("src", kthis.attr("data-src"));
xxx();
}
}
function moveproduct(k) {
if (iszoom) {
return;
}
if ($("#pro").is(":hidden")) {
} else {
//$("#blanco").show();
tmpprocurrent = procurrent + k;
if (tmpprocurrent <= 0 || tmpprocurrent > contadortotal) {
return;
}
procurrent = procurrent + k;
if (procurrent * propagination <= ashowproducts_full.length) {
fin = procurrent * propagination;
init = fin - propagination;
drawproductsarray(init, fin);
}
}
}
function formatearalbaranes(){
if (isEmpty(albformat)){
albformat=[];
}
if (!isEmpty(alb) && alb!='vacio' ){
alb.forEach(function (k, v) {
kkey=k['f'].substring(3, 4) + "" + String(k['al']).padStart(5,'0');
if ((albformat[kkey])==null){
albformat[kkey]=[];
albformat[kkey]['p']=1;
albformat[kkey]['f']=k["f"];
albformat[kkey]['e']=k["e"];
albformat[kkey]['al']=k["al"];
}
else{
albformat[kkey]['p'] +=1;
}
});
}
}
function xxx() {
//console.log("xxx");
if (window.innerHeight > window.innerWidth) {
//alert("Please use Landscape!");
Ordenar_Relacionados_Vertical();
} else {
Ordenar_Relacionados_Horizontal();
}
//$("#blanco").hide();
}
var kaltoactual = "100%";
function Ordenar_Relacionados_Vertical() {
/*
anchocol = $(".kcol").width();
kanchopro = anchocol;
ancho = $(".imgprocol").width() + $(".txtprocol").outerWidth() + parseInt($(".txtprocol").css('marginLeft'));
$(".imgprocol").css('margin-left', parseInt((anchocol - ancho) / 2))
*/
alto = $(".menufooter").offset().top - $("#separatorfixed").outerHeight() - 2;
alto = parseInt(alto);
alto = parseInt(alto * 0.4);
kaltoactual = alto + "px";
$(".imgplist").css("max-height", alto);
$(".relacionados").css("height", 0);
relacionadosh = parseInt(
$(".menufooter").offset().top -
($("#pro").offset().top + $("#pro").outerHeight())
);
$(".relacionados").css("height", relacionadosh);
if (relacionadosh < 120) {
filas = 1;
} else {
filas = 2;
}
relacionadosch = parseInt((relacionadosh - 2 * filas) / filas);
relacionadoscw = parseInt(($("#pro").width() - 8 * 2) / 3);
//$(".soyrelacionado").css('height', relacionadosch);
$(".soyrelacionado").css("width", relacionadoscw);
//console.log("gato" + parseInt($(".logistica").offset().top + $(".logistica").height()) - parseInt($(".menufooter").offset().top));
$(".soyrelacionado").css("width", relacionadoscw);
}
function drawconsumos() {
$(".consumoproducto").each(function (index) {
//console.log(index + ": " + $(this).attr("data-id"));
//console.log($(this).html())
if (!isEmpty(con)) {
consumo = con[$(this).attr("data-id")];
if (consumo == null) {
} else {
if (con[$(this).attr("data-id")][-1] == null) {
} else {
$(this)
.children()
.html(formatprice(con[$(this).attr("data-id")][-1], 0));
$(this).show();
}
}
}
});
drawcantidadpedida();
}
function drawcantidadpedida() {
$(".pedidoproducto").each(function (index) {
////console.log(index + ": " + $(this).attr("data-id"));
consumo = aproduct[$(this).attr("data-id")];
if (consumo == null) {
$(this).hide();
} else {
cantidad = dimecantidad($(this).attr("data-id"));
if (cantidad == 0) {
$(this).hide();
} else {
$(this).html(formatprice(cantidad, 0));
$(this).show();
}
}
});
}
var fechajson = "";
var fechajsonag = "";
function tableclientesagente(){
htmlres =
"";
htmlres += "";
htmlres +=
"";
htmlres += "";
htmlres += "";
$.each(cliag, function (index, valor) {
nom = trimChar(valor["nom"], " ");
if (trimChar(valor["com"], " ") != nom && !isEmpty(valor["com"])) {
nom += "" + trimChar(valor["com"], " ") + "
";
}
htmlres +=
"";
htmlres +=
"';
("");
});
htmlres += "";
htmlres += "ID NOMBRE CIUDAD PAIS " +
index +
" " +
nom +
" " +
valor["city"] +
" " +
valor["country"] +
"
";
return htmlres;
}
function mostrarclientesagente() {
$("#MaxModalTitle").html("Clientes");
$("#MaxModal").attr("data-tipo", "clientesagente");
$("#MaxModal").modal("show");
$("#blanco").hide();
htmlres="";
if (typeof Customtableclientesagente === "function") {
htmlres+=Customtableclientesagente();
} else {
htmlres+=tableclientesagente();
}
setTimeout(function () {
transaction = midb.transaction("kli");
klis = transaction.objectStore("kli"); // (2)
request = klis.openCursor();
request.onsuccess = function () {
let cursor = request.result;
if (cursor) {
//console.log(cursor.key);
$(".unkli" + cursor.key).addClass("isoffline");
cursor.continue();
} else {
//console.log("No hay más libros");
}
};
$("#tablecliag").DataTable({
paging: false,
ordering: true,
info: false,
});
}, 500);
$(".maxmodalbody").html(htmlres);
}
function utf8_to_b64(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
function b64_to_utf8(str) {
return decodeURIComponent(escape(window.atob(str)));
}
function loadDataClientEnd(data, isoffline) {
$("#nologin").hide();
var items = [];
fechajson = data["date"];
$(".fechajson").html(fechajson);
aproduct = data["p"];
afam = data["f"];
apo = data["po"];
rel = data["r"];
con = data["cons_ano"];
alb = data["alb"];
adr = data["ad"];
pref = data["pref"];
cli = data["cli"];
cartera = data["cartera"];
sts = data["sts"];
tventas = data["tv"];
cnf = data["cnf"];
pst = data["pst"];
psc = data["psc"];
famfilter();
purgadatos();
$.each(aproduct, function (k, v) {
if (!isEmpty(psc) && psc[k] != null) {
aproduct[k]["p"] = psc[k];
} else if (!isEmpty(pst) && pst[k] != null) {
aproduct[k]["p"] = pst[k];
}
});
albformat=[];
formatearalbaranes();
drawfams(-1);
MapeoAcciones();
MapeoAcciones();
$("#login").hide();
$("#pro").hide();
$("#main").show();
$("#cat").show();
$(".namefamilia").hide();
$(".paginascount").hide();
$("#clisinf").html("" + cli["idmon"] + " " + cli["nom"]);
if (typeof CustomPostLoadData === "function") {
CustomPostLoadData();
}
if (isoffline) {
$("body").addClass("offline");
$("body").removeClass("online");
} else {
$("body").addClass("online");
$("body").removeClass("offline");
}
transaction = midb.transaction("kpd");
kpds = transaction.objectStore("kpd");
request = kpds.get(localcli);
request.onerror = function () {
console.error("Error", request.error);
$("#blanco").hide();
loadcorazones();
};
request.onsuccess = function () {
gatorrrr = request.result;
if (!isEmpty(gatorrrr)) {
data = gatorrrr["json"];
localpedido = JSON.parse(data);
}
$("#blanco").hide();
loadcorazones();
};
drawpedidostimer = setTimeout(drawpedidos, 1000);
}
var acliagoff = [];
var cuantosklioffline = 0;
var cuantoskliofflineok = 0;
var cuantoskliofflineerror = 0;
function DescargarClientesOffline() {
acliagoff = [];
cuantosklioffline = 0;
cuantoskliofflineok = 0;
cuantoskliofflineerror = 0;
$.each(cliag, function (index, valor) {
acliagoff.push(index);
cuantosklioffline++;
});
DescargarClientesOfflineContinua();
}
function DescargarClientesOfflineContinua() {
if (!cimgprogresscontinue) {
return;
}
$(".ckliok").html(cuantoskliofflineok);
$(".cklierror").html(cuantoskliofflineerror);
$(".cklitotal").html(cuantosklioffline);
$(".cklip").html(cuantoskliofflineok + cuantoskliofflineerror);
tmpxx = cuantoskliofflineok + cuantoskliofflineerror;
porcent = Math.round((tmpxx * 100) / cuantosklioffline);
$("#kliprogress").attr("aria-valuenow", porcent);
$("#kliprogress").attr("style", "width: " + porcent + "%");
$("#kliprogress").html(porcent + "%");
if (acliagoff.length > 0) {
LoadDataForOffline(acliagoff.pop(), "json");
}
}
function BorrarClientesOffline() {
transaction = midb.transaction("kli", "readwrite");
klis = transaction.objectStore("kli"); // (2)
klis.clear();
}
function LoadDataForOffline(kcli, cual) {
tmph = localag + "|" + kcli + "|" + currentswversion + "|" + kcontra;
tmph = utf8_to_b64(tmph);
$.ajax({
dataType: "json",
url: cual + "/" + kcli,
headers: {
"X-Myapp-Nonce": tmph,
},
})
.done(function (data) {
if (data["OK"] > 0) {
//localStorage.setItem("kli" + kcli, JSON.stringify(data));
transaction = midb.transaction("kli", "readwrite");
klis = transaction.objectStore("kli"); // (2)
kliinsert = { id: kcli, json: data };
request = klis.put(kliinsert); // (3)
request.onsuccess = function () {
// (4)
cuantoskliofflineok++;
DescargarClientesOfflineContinua();
};
request.onerror = function () {
console.log("Error", request.error);
console.log(kcli + "KO 7");
cuantoskliofflineerror++;
DescargarClientesOfflineContinua();
};
} else {
console.log(kcli + "KO 1");
cuantoskliofflineerror++;
DescargarClientesOfflineContinua();
}
})
.fail(function (jqXHR, textStatus, xhr) {
console.log(kcli + "KO 2");
cuantoskliofflineerror++;
DescargarClientesOfflineContinua();
});
}
function LoadData(kcli, cual) {
$("#MaxModal").modal("hide");
$("#blanco").show();
$(".ncart").hide();
if (kcli.startsWith("ag")) {
tmph =
kcli.substring(2, 1000) +
"|" +
"-1" +
"|" +
currentswversion +
"|" +
kcontra;
tmph = utf8_to_b64(tmph);
$.ajax({
dataType: "json",
url: cual + "/" + kcli,
headers: {
"X-Myapp-Nonce": tmph,
},
})
.done(function (data) {
if (data["OK"] > 0) {
transaction = midb.transaction("kli", "readwrite");
klis = transaction.objectStore("kli"); // (2)
kliinsert = { id: kcli, json: data };
request = klis.put(kliinsert); // (3)
cliag = data["c"];
fechajson = data["date"];
localag = kcli.substring(2, 1000);
if (STOCKAGENTE == "1" && localag > 0) {
cliagstk = data["s"];
}
mostrarclientesagente();
$(".soloagente").show();
$("#nologin").hide();
} else {
$("#login").show();
$("#blanco").hide();
$("#nologin").show();
}
})
.fail(function (data, rescode) {
transaction = midb.transaction("kli");
klis = transaction.objectStore("kli");
request = klis.get(kcli);
request.onerror = function () {
console.error("Error", request.error);
$("#login").show();
$("#blanco").hide();
$("#nologin").show();
};
request.onsuccess = function () {
gatorrrr = request.result;
if (!isEmpty(gatorrrr)) {
data = gatorrrr["json"];
cliag = data["c"];
fechajson = data["date"];
localag = kcli.substring(2, 1000);
if (STOCKAGENTE == "1" && localag > 0) {
cliagstk = data["s"];
}
$(".soloagente").show();
mostrarclientesagente();
$("#nologin").hide();
} else {
$("#login").show();
$("#blanco").hide();
$("#nologin").show();
}
// continúa trabajando con la base de datos usando el objeto db
};
});
/*
$.getJSON(cual + "/" + kcli, function (data) {
=data['c'];
fechajson=data['date'];
localag=kcli.substring(2, 1000);
mostrarclientesagente();
}).fail(function() {
$("#login").show();
$("#blanco").hide();
$('#nologin').show();
});
*/
} else {
tmph = localag + "|" + kcli + "|" + currentswversion + "|" + kcontra;
tmph = utf8_to_b64(tmph);
$.ajax({
dataType: "json",
url: cual + "/" + kcli,
headers: {
"X-Myapp-Nonce": tmph,
},
})
.done(function (data) {
if (data["OK"] > 0) {
transaction = midb.transaction("kli", "readwrite");
klis = transaction.objectStore("kli"); // (2)
kliinsert = { id: kcli, json: data };
request = klis.put(kliinsert); // (3)
localcli = kcli;
loadDataClientEnd(data, 0);
} else {
$("#login").show();
$("#blanco").hide();
$("#nologin").show();
}
})
.fail(function (jqXHR, textStatus, xhr) {
transaction = midb.transaction("kli");
klis = transaction.objectStore("kli");
request = klis.get(kcli);
request.onerror = function () {
console.error("Error", request.error);
$("#login").show();
$("#blanco").hide();
$("#nologin").show();
};
request.onsuccess = function () {
gatorrrr = request.result;
if (!isEmpty(gatorrrr)) {
data = gatorrrr["json"];
localcli = kcli;
loadDataClientEnd(data, 1);
} else {
$("#login").show();
$("#blanco").hide();
$("#nologin").show();
}
// continúa trabajando con la base de datos usando el objeto db
};
});
}
if(COBRARCARTERA=='1' && localag > 0){
$('#botoncobros').show();
}
else{
$('#botoncobros').hide();
}
}
/*
function listenForWaitingServiceWorker(reg, callback) {
function awaitStateChange() {
reg.installing.addEventListener('statechange', function() {
if (this.state === 'installed') callback(reg);
});
}
if (!reg) return;
if (reg.waiting) return callback(reg);
if (reg.installing) awaitStateChange();
reg.addEventListener('updatefound', awaitStateChange);
}
// reload once when the new Service Worker starts activating
var refreshing;
navigator.serviceWorker.addEventListener('controllerchange',
function() {
if (refreshing) return;
refreshing = true;
window.location.reload();
}
);
function promptUserToRefresh(reg) {
// this is just an example
// don't use window.confirm in real life; it's terrible
if (window.confirm("New version available! OK to refresh?")) {
reg.waiting.postMessage('skipWaiting');
}
}
listenForWaitingServiceWorker(reg, promptUserToRefresh);
*/
function updatesw() {
swreg.unregister().then((unregResult) => {
if (navigator.app) {
navigator.app.exitApp();
}
window.location.reload();
});
}
function drawcontador() {
$(".paginascount").html(contadorposicion + 1 + "/" + contadortotal);
}
function Ordenar_Relacionados_Horizontal() {
if ($(".logistica").length) {
/*
anchocol = $(".kcol").width();
kanchopro = anchocol;
ancho = $(".imgprocol").width() + $(".txtprocol").outerWidth() + parseInt($(".txtprocol").css('marginLeft'));
$(".imgprocol").css('margin-left', parseInt((anchocol - ancho) / 2))
*/
$(".relacionados").css("height", 0);
relacionadosh = parseInt(
$(".menufooter").offset().top - $("#pro").offset().top
);
$(".relacionados").css("height", relacionadosh);
relacionadosw = parseInt($(".relacionados").width() - 20);
if (relacionadosw < 560) {
filas = 3;
} else {
filas = 3;
}
//relacionadosch=parseInt((relacionadosh-2*filas)/filas);
relacionadoscw = parseInt(($(".relacionados").width() - 20) / filas);
//$(".soyrelacionado").css('height', relacionadosch);
$(".soyrelacionado").css("width", relacionadoscw);
dif =
parseInt($(".logistica").offset().top + $(".logistica").height()) -
parseInt($(".menufooter").offset().top);
kaltoactual = "100%";
if (dif > 0) {
//console.log("Resto imagen");
maxhimg = parseInt($(".imgplist").height()) - (dif + 10);
$(".imgplist").css("max-width", maxhimg);
}
}
}
$(window).resize(function () {
anchocol = $(".kcol").width();
if (kanchopro != anchocol) {
kanchopro = anchocol;
xxx();
}
});
var EsTactil = 0;
var midb;
$(document).ready(function () {
supportsTouchx = "ontouchstart" in window || navigator.msMaxTouchPoints;
if (!isEmpty(supportsTouchx) || supportsTouchx == true) {
EsTactil = 1;
}
$("body").addClass("tactil" + EsTactil);
imgonerror();
/*
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/n/sw.js')
.then(() => { console.log('Service Worker Registered'); });
}
*/
var midbopenrequest = indexedDB.open("db" + appclient, 4);
// crea/actualiza la base de datos sin chequeo de versiones
midbopenrequest.onupgradeneeded = function () {
midb = midbopenrequest.result;
if (!midb.objectStoreNames.contains("kli")) {
// si no hay un almacén de libros ("books"),
midb.createObjectStore("kli", { keyPath: "id" }); // crearlo
}
if (!midb.objectStoreNames.contains("kpd")) {
// si no hay un almacén de libros ("books"),
midb.createObjectStore("kpd", { keyPath: "id" }); // crearlo
}
if (!midb.objectStoreNames.contains("khe")) {
// si no hay un almacén de libros ("books"),
midb.createObjectStore("khe", { keyPath: "id" }); // crearlo
}
if (!midb.objectStoreNames.contains("kpds")) {
// si no hay un almacén de libros ("books"),
var objectStore = midb.createObjectStore("kpds", {
keyPath: "id",
autoIncrement: true,
}); // crearlo
objectStore.createIndex("idcli", "idcli", { unique: false });
}
};
midbopenrequest.onerror = function () {
console.error("Error", midbopenrequest.error);
};
midbopenrequest.onsuccess = function () {
midb = midbopenrequest.result;
// continúa trabajando con la base de datos usando el objeto db
};
// make the whole serviceworker process into a promise so later on we can
// listen to it and in case new content is available a toast will be shown
window.isUpdateAvailable = new Promise(function (resolve, reject) {
// lazy way of disabling service workers while developing
if (
"serviceWorker" in navigator &&
["localhost", "127"].indexOf(location.hostname) === -1
) {
// register service worker file
navigator.serviceWorker
.register("sw.php")
.then((reg) => {
swreg = reg;
reg.onupdatefound = () => {
const installingWorker = reg.installing;
installingWorker.onstatechange = () => {
console.log("Instalando Worker");
switch (installingWorker.state) {
case "installed":
if (navigator.serviceWorker.controller) {
console.log("UPDATE");
alert(
"Hay una actulizacion Reinicie el programa por favor"
);
resolve(true);
} else {
console.log("NOUPDATE");
// no update available
resolve(false);
}
break;
}
};
};
console.log("Registration succeeded. Scope is " + reg.scope);
$.getJSON("swversion", function (data) {
currentswversion = data["swversion"];
$(".swversionn").html(data["swversion"]);
if ($("#hwversion").html() != data["swversion"]) {
$(".updateversion").show();
}
});
})
.catch((err) => console.error("[SW ERROR]", err));
}
});
setInterval(function () {
$.getJSON("swversion", function (data) {
currentswversion = data["swversion"];
$(".swversionn").html(data["swversion"]);
if ($("#hwversion").html() != data["swversion"]) {
$(".updateversion").show();
}
}).fail(function (event, jqxhr, exception) {
if (event.status == 404) {
window.location.reload();
}
});
}, 3000);
// Update:
// this also can be incorporated right into e.g. your run() function in angular,
// to avoid using the global namespace for such a thing.
// because the registering of a service worker doesn't need to be executed on the first load of the page.
/*
window.addEventListener("beforeinstallprompt", function(e) {
// log the platforms provided as options in an install prompt
console.log(e.platforms); // e.g., ["web", "android", "windows"]
e.userChoice.then(function(choiceResult) {
console.log(choiceResult.outcome); // either "accepted" or "dismissed"
}, handleError);
});
*/
/*
window.addEventListener('beforeinstallprompt', (e) => {
alert("gato");
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI to notify the user they can add to home screen
$("#installapp").show();
$("#installapp").click(function () {
$("#installapp").hide();
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
});
*/
document.onkeydown = checkKey;
$("#pro").on("swipeleft", function () {
moveproduct(1);
});
$("#pro").on("swiperight", function () {
moveproduct(-1);
});
$(document).bind("touchmove", function (e) {
e.preventDefault();
});
document.addEventListener("touchmove", function (event) {
event.preventDefault();
});
// later on when you actually want to play a sound at any point without user interaction
soundEffect.src = "./sound/click.ogg";
var win = $(window);
$("#buscador").submit(function (event) {
//console.log("busco");
buscador($("#search").val());
event.preventDefault();
});
/*
// Each time the user scrolls
win.scroll(function () {
alert("xxx");
// End of the document reached?
//$(".debug").html($(document).height() + ' ' + win.height() + ' ' + win.scrollTop() + ' ' + screen.availHeight);
if (($(document).height() - win.height()) - 40 < win.scrollTop()) {
if ($('#pro').is(':hidden')) {
alert("fin");
}
else {
$('.rowpro').html("");
if (procurrent * propagination < ashowproducts.length) {
procurrent = procurrent + 1;
fin = procurrent * propagination;
init = fin - propagination;
drawproductsarray(init, fin);
}
}
}
});
*/
MapeoAcciones();
});
function MapeoAcciones() {
$(".action").off("click");
$(".action").click(function () {
ActionClick($(this));
});
$("img").off("error");
$("img").on("error", function () {
$(this).attr("src", "/img/offline.jpg");
});
}
function draweconomia(direccion) {
economia = "";
m0 = 0;
m1 = 0;
y0 = 0;
y1 = 0;
m0_0 = 0;
m1_0 = 0;
y0_0 = 0;
y1_0 = 0;
m0_2 = 0;
m1_2 = 0;
y0_2 = 0;
y1_2 = 0;
classeco = "";
if (direccion >= 0) {
classeco = " ecodirect";
}
sts.forEach(function (k, v) {
if ((direccion >= 0 && parseInt(k["e"]) == direccion) || direccion == -1) {
if (k["t"] == "M0") {
m0 += parseInt(k["b"]);
if (parseInt(k["s"]) == 0) {
m0_0 += parseInt(k["b"]);
} else {
m0_2 += parseInt(k["b"]);
}
}
if (k["t"] == "M1") {
m1 += parseInt(k["b"]);
if (parseInt(k["s"]) == 0) {
m1_0 += parseInt(k["b"]);
} else {
m1_2 += parseInt(k["b"]);
}
}
if (k["t"] == "Y0") {
y0 += parseInt(k["b"]);
if (parseInt(k["s"]) == 0) {
y0_0 += parseInt(k["b"]);
} else {
y0_2 += parseInt(k["b"]);
}
}
if (k["t"] == "Y1") {
y1 += parseInt(k["b"]);
if (parseInt(k["s"]) == 0) {
y1_0 += parseInt(k["b"]);
} else {
y1_2 += parseInt(k["b"]);
}
}
}
});
m = parseInt((100 * m0) / m1) - 100;
y = parseInt((100 * y0) / y1) - 100;
m_0 = parseInt((100 * m0_0) / m1_0) - 100;
y_0 = parseInt((100 * y0_0) / y1_0) - 100;
m_2 = parseInt((100 * m0_2) / m1_2) - 100;
y_2 = parseInt((100 * y0_2) / y1_2) - 100;
if (isNaN(m)) m = 100;
if (isNaN(y)) y = 100;
if (isNaN(m_0)) m_0 = 100;
if (isNaN(y_0)) y_0 = 100;
if (isNaN(m_2)) m_2 = 100;
if (isNaN(y_0)) y_0 = 100;
if (m > 0) {
m = "+" + m + "% ";
} else {
m = "" + m + "% ";
}
if (y > 0) {
y = "+" + y + "% ";
} else {
y = "" + y + "% ";
}
if (m_0 > 0) {
m_0 = "+" + m_0 + "% ";
} else {
m_0 = "" + m_0 + "% ";
}
if (y_0 > 0) {
y_0 = "+" + y_0 + "% ";
} else {
y_0 = "" + y_0 + "% ";
}
if (m_2 > 0) {
m_2 = "+" + m_2 + "% ";
} else {
m_2 = "" + m_2 + "% ";
}
if (y_2 > 0) {
y_2 = "+" + y_2 + "% ";
} else {
y_2 = "" + y_2 + "% ";
}
economia +=
"";
economia +=
"";
//economia += "";
//economia += "";
economia +=
"";
economia += "Sucursal Año Natural Actual Año Natural Anterior Año en curso Actual Año en curso Anterior Empresa2 " + formatprice(m0_2, 0) + " " + formatprice(m1_2, 0) + " " + m_2 + " " + formatprice(y0_2, 0) + " " + formatprice(y1_2, 0) + " " + y_2 + " Empresa0 " + formatprice(m0_0, 0) + " " + formatprice(m1_0, 0) + " " + m_0 + " " + formatprice(y0_0, 0) + " " + formatprice(y1_0, 0) + " " + y_0 + " GENERAL " +
formatprice(m0, 0) +
" " +
formatprice(m1, 0) +
" " +
m +
" " +
formatprice(y0, 0) +
" " +
formatprice(y1, 0) +
" " +
y +
"
";
return economia;
}
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
function findcantidadtventas(idp) {
tventas[2].forEach(function (k, v) {
idprotmp = productbyref(k["a"]);
if (idprotmp != -1) {
if (idprotmp == idp) {
return k["t"];
}
}
});
tventas[0].forEach(function (k, v) {
idprotmp = productbyref(k["a"]);
if (idprotmp != -1) {
if (idprotmp == idp) {
return k["t"];
}
}
});
return;
}
//variables para la descarga de imganes
var cuantasloaded = 0;
var cuantas = 0;
var cuantaserror = 0;
var cuantastotal = 0;
var cimgprogresscontinue = 0;
function loadimgcache(donde) {
if (cimgprogresscontinue == 0) {
return;
}
dondefin = donde + 20;
cuantosp = Object.keys(aproduct).length;
if (donde == 0) {
$("span.cimgtotal").html(cuantosp);
cuantastotal = cuantosp;
}
nocontinuo = 0;
if (dondefin > cuantosp) {
nocontinuo = 1;
dondefin = cuantosp;
}
for (i = donde; i < dondefin; i++) {
cuantas += 1;
var tmp = new Image();
tmp.onload = function () {
cuantasloaded += 1;
updatecimgprogress();
if (cuantasloaded + cuantaserror == cuantas) {
if (nocontinuo == 0) {
setTimeout(function () {
loadimgcache(donde + 20);
}, 100);
}
}
//console.log(cuantas + " -> " + cuantasloaded);
};
tmp.onerror = function () {
cuantaserror += 1;
updatecimgprogress();
if (cuantasloaded + cuantaserror == cuantas) {
if (nocontinuo == 0) {
setTimeout(function () {
loadimgcache(donde + 20);
}, 100);
}
}
};
tmp.src = getpimg(aproduct[Object.keys(aproduct)[i]]["im"]);
//console.log(cuantas + " -> " + cuantasloaded);
$("span.cimg").html(cuantas);
}
}
function updatecimgprogress() {
tmpxx = cuantasloaded + cuantaserror;
porcent = Math.round((tmpxx * 100) / cuantastotal);
$("span.cimgok").html(cuantasloaded);
$("span.cimgerror").html(cuantaserror);
$("#imgprogress").attr("aria-valuenow", porcent);
$("#imgprogress").attr("style", "width: " + porcent + "%");
$("#imgprogress").html(porcent + "%");
}
function ActionClick(object) {
att = object.attr("data-action");
$("#MenuModal").modal("hide");
if (att == "familia") {
window.scrollTo(0, 0);
kfam = object.attr("data-id");
$("#cat").hide();
$("#pro").hide();
$("#prolist").show();
$("#OptionModal").modal("hide");
drawproductsfam(kfam);
//drawproductsfamlist(kfam);
} else if (att == "productgoto") {
kfam = object.attr("data-famid");
kproduct = object.attr("data-productid");
gotoproduct(kfam, kproduct, kproduct);
} else if (att == "login") {
window.scrollTo(0, 0);
kcontra = $("#kpass").val();
LoadData($("#kusuario").val(), "json");
/*
$("#login").hide();
$("#pro").hide();
$("#main").show();
$("#cat").show();
$('.namefamilia').hide();
$('.paginascount').hide();
*/
} else if (att == "familiatit") {
kfam = object.attr("data-id");
drawfams(kfam);
} else if (att == "inicio") {
drawfams(-1);
$("#login").hide();
$("#pro").hide();
$("#main").show();
$("#cat").show();
$(".namefamilia").hide();
$(".paginascount").hide();
} else if (att == "logout") {
window.scrollTo(0, 0);
$("#login").show();
$("#pro").hide();
$("#main").hide();
$("#cat").hide();
localag = "-1";
cliag = null;
cliagstk = null;
localcli = null;
$(".soloagente").hide();
} else if (att == "test") {
alert(
$(document).height() +
" -> " +
$(window).height() +
" -> " +
$(window).scrollTop()
);
} else if (att == "plus") {
moveproduct(1);
} else if (att == "minus") {
moveproduct(-1);
} else if (att == "menu") {
$("#MenuModal").modal("show");
} else if (att == "familias") {
drawfams(-1);
} else if (att == "buscar") {
$("#BuscaModal").modal("show");
} else if (att == "reload") {
//window.scrollTo(0, 0);
//$("#blanco").show();
//LoadData($("#kusuario").val(), "jsonr");
$("#MaxModalTitle").html("Reload Imgs");
$("#MaxModal").attr("data-tipo", "reloadimgs");
$("#MaxModal").modal("show");
htmlres = "";
cuantas = 0;
cuantasloaded = 0;
cuantaserror = 0;
htmlres = "";
htmlres +=
'';
htmlres += "";
htmlres +=
'0 ';
htmlres += '0 ';
htmlres +=
'0 ';
htmlres += '0 ';
htmlres += "
";
htmlres +=
"Descargar Imagenes ";
if (localag > 0) {
htmlres += " ";
htmlres +=
'';
htmlres += "";
htmlres +=
'0 ';
htmlres +=
'0 ';
htmlres +=
'0 ';
htmlres += '0 ';
htmlres += "
";
htmlres +=
"Descargar Clientes ";
htmlres += " ";
htmlres +=
"Borrar Clientes Offline ";
}
$(".maxmodalbody").html(htmlres);
cuantasloaded = 0;
cuantas = 0;
cuantaserror = 0;
cuantastotal = 0;
cimgprogresscontinue = 1;
$("#MaxModal").on("hidden.bs.modal", function (e) {
$("#MaxModal").off("hidden.bs.modal");
cimgprogresscontinue = 0;
});
/*
setTimeout(function () {
loadimgcache(0);
}, 200);
*/
} else if (att == "tools") {
$("#MaxModalTitle").html("Herramientas");
$("#MaxModal").attr("data-tipo", "herramientas");
$("#MaxModal").modal("show");
htmlres = "Espacio Ocupado:" + localStorageSpace();
htmlres +=
" Chequer Espacio: Checkear ";
htmlres += " ";
htmlres += window.localStorage.remainingSpace;
htmlres += " ";
htmlres +=
"document.body.client:" +
document.body.clientWidth +
"x" +
document.body.clientHeight +
" ";
htmlres += "screen:" + screen.width + "x" + screen.height + " ";
htmlres +=
"screen.avail:" + screen.availWidth + "x" + screen.availHeight + " ";
htmlres +=
"window.inner:" + window.innerWidth + "x" + window.innerHeight + " ";
htmlres +=
"window.outer:" + window.outerWidth + "x" + window.outerHeight + " ";
htmlres += " ";
supportsTouch = "ontouchstart" in window || navigator.msMaxTouchPoints;
htmlres += "Touch:" + supportsTouch + " ";
htmlres += "Touch Init:" + EsTactil + " ";
/*
document.body.clientHeight // Inner height of the HTML document body, including padding
// but not the horizontal scrollbar height, border, or margin
screen.height // Device screen height (i.e. all physically visible stuff)
screen.availHeight // Device screen height minus the operating system taskbar (if present)
window.innerHeight // The current document's viewport height, minus taskbars, etc.
window.outerHeight
*/
$(".maxmodalbody").html(htmlres);
} else if (att == "buscador") {
kbusco = $("#kbusco").val();
buscador(kbusco);
} else if (att == "heart") {
$("#MaxModalTitle").html("Favoritos");
$("#MaxModal").attr("data-tipo", "favoritos");
$("#MaxModal").modal("show");
itemsheart = [];
$.each(aproduct, function (key, val) {
//console.log(key);
//console.log(val);
heart = val["cz"];
if (heart == 1) {
itemsheart.push(key);
}
});
tittemp =
' ';
tittemp += " Favoritos [" + itemsheart.length + "]";
tittemp +=
'Borrar Todos ';
$("#MaxModalTitle").html(tittemp);
htmlres = "";
$.each(itemsheart, function (key, val) {
//console.log(key + " <<>> " + val);
htmlres += DrawProductList2(val);
});
htmlres += "";
htmlres = gettablehead("tableheart") + htmlres;
$(".maxmodalbody").html(htmlres);
if (STOCKAGENTE == "1" && localag > 0) {
$.each(itemsheart, function (key, val) {
//console.log(key + " <<>> " + val);
loadlotes(val);
});
}
} else if (att == "cartera") {
$("#MaxModalTitle").html("Cartera Cliente");
$("#MaxModal").attr("data-tipo", "Cartera");
$("#MaxModal").modal("show");
hayheader = 0;
htmlres = "";
moneda = "€";
importe = 0;
htmlres += '';
htmlrestemp="No hay Cartera";
if(COBRARCARTERA=='1' && localag > 0){
htmlrestemp+= "
COBRAR ALBARAN ";
}
$(".maxmodalbody").html(htmlrestemp);
if (!isEmpty(cartera) && cartera != "vacio") {
cartera.forEach(function (k, v) {
if (k["SUCURSAL"] == SUCURSAL1 || SUCURSAL1== -1 ) {
if (hayheader == 0) {
htmlres += headercartera(0);
hayheader = 1;
}
importe += parseFloat(k["IMPORTE"]);
htmlres +=
"" +
pad(k["ENVIO"], 2) +
"*" +
k["FECHA"] +
"" +
k["VENCIMIENTO"] +
"" +
k["FACTURA"] +
"" +
k["REFERENCIA"] +
"" +
formatprice(k["IMPORTE"], 2) +
"";
htmlres += "";
if (k["REC"] == 1) {
htmlres +=
'
';
}
htmlres += "";
if (k["FACTURA"] != "") {
htmlres +=
'
';
}
if(COBRARCARTERA=='1' && localag > 0){
htmlres+= "
COBRAR ";
}
htmlres += "";
if (!isEmpty(k["NOTAS"])) {
htmlres += "";
htmlres +=
"" +
k["NOTAS"] +
"";
htmlres += "";
} else {
htmlres += "";
htmlres += "";
htmlres += "";
}
}
});
if (hayheader == 1) {
htmlres += footercartera(importe, moneda, 0);
htmlres += "
";
}
hayheader = 0;
importe = 0;
moneda = "€";
cartera.forEach(function (k, v) {
if (k["SUCURSAL"] == SUCURSAL2 && SUCURSAL1!= -1) {
if (hayheader == 0) {
htmlres += headercartera(2);
hayheader = 1;
}
importe += parseFloat(k["IMPORTE"]);
htmlres +=
"" +
pad(k["ENVIO"], 2) +
"*" +
k["FECHA"] +
"" +
k["VENCIMIENTO"] +
"" +
k["FACTURA"] +
"" +
formatprice(k["P_DTO_ESP"], 2) +
"" +
formatprice(k["P_DTO_PP"], 2) +
"" +
formatprice(k["IMPORTE"], 2) +
"";
htmlres += "";
if (k["REC"] == 1) {
htmlres +=
'
';
}
htmlres += "";
if (k["FACTURA"] != "") {
htmlres +=
'
';
}
htmlres += "";
if (!isEmpty(k["NOTAS"])) {
htmlres += "";
htmlres +=
"" +
k["NOTAS"] +
"";
htmlres += "";
} else {
htmlres += "";
htmlres += "";
htmlres += "";
}
}
});
if (hayheader == 1) {
htmlres += footercartera(importe, moneda, 2);
}
if(COBRARCARTERA=='1' && localag > 0){
htmlres+= "
COBRAR ALBARAN ";
}
htmlres += "
";
htmlres += " ";
htmlres += GetDirecciones();
$(".maxmodalbody").html(htmlres);
MapeoAcciones();
}
} else if (att == "albaranes") {
$("#MaxModalTitle").html("Albaranes Cliente");
$("#MaxModal").attr("data-tipo", "Albaranes");
$("#MaxModal").modal("show");
$(".maxmodalbody").html("Cargando Albaranes ....");
htmlres="";
albformat.forEach(function (k, v) {
htmlres = ""+k['al']+""+k['f']+""+k['p']+""+k['e']+"*" + htmlres;
});
htmlres="" + htmlres;
htmlres +="Numero Fecha Lineas Direccion
";
htmlres += " ";
htmlres += GetDirecciones();
$(".maxmodalbody").html(htmlres);
MapeoAcciones();
} else if (att == "infocliente") {
$("#MaxModalTitle").html("Informacion Cliente");
$("#MaxModal").modal("show");
tarifas = "";
/*
Forma de pago: 1 PAGARE a 30 c
Dto. Comercial: 0 d
Dto. Comercial 2: 0 e
Dto. Especial: 17.35 f
Dto. Pronto Pago: 5 g
*/
tarifas += "";
/*la tarifa solo la vera el comercial*/
/*tarifas += "";*/
tarifas += "";
tarifas += "";
tarifas +=
"";
tarifas +=
"";
tarifas +=
"";
tarifas +=
"";
tarifas += "Tarifa: " + cli['gro'] + " Agente: " + cli["idag"] + " Forma de pago: " + cli["more"]["c"] + " DTO LINEA 1: " +
formatprice(cli["more"]["d"], 2) +
" % DTO LINEA 2: " +
formatprice(cli["more"]["e"], 2) +
" % Dto. Especial: " +
formatprice(cli["more"]["f"], 2) +
" % Dto. Pronto Pago: " +
formatprice(cli["more"]["g"], 2) +
" %
";
facturacion = "";
/*
Forma de pago: 1 PAGARE a 30 c
Dto. Comercial: 0 d
Dto. Comercial 2: 0 e
Dto. Especial: 17.35 f
Dto. Pronto Pago: 5 g
*/
facturacion += "";
facturacion += "";
facturacion += "";
facturacion += "";
facturacion += "";
facturacion += "";
facturacion += "";
facturacion += "";
facturacion += "";
facturacion +=
"";
facturacion += "Razon Social: " + cli["nom"] + " Nombre Comercial: " + cli["com"] + " CIF: " + cli["cif"] + " Direccion: " + "-" + " Poblacion: " + cli["city"] + " Provincia: " + "-" + " Pais: " + "-" + " Telefono: " + "-" + " EMail: " +
cli["mail"] +
"
";
direcciones = "";
direcciones +=
"";
adr.forEach(function (k, v) {
direcciones +=
"";
direcciones += "";
direcciones += "";
direcciones += "";
direcciones += "";
direcciones += "";
direcciones +=
"";
direcciones +=
"";
direcciones += "";
//direcciones += "" + k["ali"].substring(1) + "* : " + k["ad"] + ", " + k["cp"] + ", " + k["city"] + ", " + k["pais"] + " ";
});
direcciones += "Direccion " +
k["ali"].substring(1) +
" Nombre: " + k["company"] + " Direccion: " + k["ad"] + " CP.: " + k["cp"] + " Ciudad: " + k["city"] + " Pais: " + k["pais"] + " Telefono 1: " +
k["phone"] +
" Telefono 2: " +
k["phone_mobile"] +
"
";
economia = "";
economia += draweconomia(-1);
adr.forEach(function (k, v) {
economia += " ";
economia +=
"DIRECCION " +
k["ali"].substring(1) +
" (" +
k["ad"] +
" " +
k["cp"] +
" " +
k["city"] +
")
";
economia += draweconomia(parseInt(k["ali"].substring(1)));
});
tv = "";
tv += "";
tventas[0].forEach(function (k, v) {
//if(productbyref(k["a"])!=-1){
tv +=
"";
//}
});
tv += "" +
k["a"] +
" " +
productbyref(k["a"]) +
" " +
k["t"] +
" " +
k["p"] +
"
";
tv = " ";
tv += "";
tventas[2].forEach(function (k, v) {
//if(productbyref(k["a"])!=-1){
tv +=
"";
//}
});
tv += "" +
k["a"] +
" " +
productbyref(k["a"]) +
" " +
k["t"] +
" " +
k["p"] +
"
";
tventasa = [];
tventas[0].forEach(function (k, v) {
idprotmp = productbyref(k["a"]);
if (idprotmp != -1) {
tventasa.push(idprotmp);
}
});
tv_2 = "";
$.each(tventasa, function (key, val) {
//console.log(key + " <<>> " + val);
tv_2 += DrawProductList2(val);
});
tv_2 += "";
tv_2 = gettablehead("tabletv") + tv_2;
htmlres =
`
`;
$(".maxmodalbody").html(htmlres);
//$('div.plist[data-id="' + idp + '"]').find('div.listUnidades').html(formatprice(ori, 0))
/*$("table.tabletv tr").each(function () {
idp=$(this).attr("data-id");
if(idp!==undefined)
{
$(this).find('.refaddon').html(findcantidadtventas(idp));
}
});
*/
tventas[2].forEach(function (k, v) {
idprotmp = productbyref(k["a"]);
if (idprotmp != -1) {
$('table.tabletv tr[data-id="' + idprotmp + '"]')
.find(".refaddon")
.html("[" + formatprice(k["t"], 0) + "]");
}
});
tventas[0].forEach(function (k, v) {
idprotmp = productbyref(k["a"]);
if (idprotmp != -1) {
$('table.tabletv tr[data-id="' + idprotmp + '"]')
.find(".refaddon")
.html("[" + formatprice(k["t"], 0) + "]");
}
});
} else if (att == "cart") {
$("#MaxModalTitle").html("Pedido");
$("#MaxModal").attr("data-tipo", "pedido");
$("#MaxModal").modal("show");
itemsheart = [];
itemsheart = ordenarproductos(getlistapedidos());
tittemp =
'
';
tittemp += " Pedido [" + itemsheart.length + "]";
$("#MaxModalTitle").html(tittemp);
htmlres = "";
totaldinero = 0;
volumentotal = 0;
unidadestotal=0;
$.each(itemsheart, function (key, val) {
//console.log(key + " <<>> " + val);
htmlres += DrawProductList2(val);
totaldinero += getTotalLinea(val);
unidadestotal+=dimecantidad(val);
volumentotal +=
(getVolume(val) * dimecantidad(val)) / getFloatProductValue(val, "u5");
});
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "TOTAL";
htmlres += ""+unidadestotal+"";
if (STOCKAGENTE == "1" && localag > 0) {
htmlres += "";
}
htmlres += "";
htmlres +=
"" +
formatprice(totaldinero, 2) +
"";
//htmlres += "";
htmlres += "";
/*
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "Volumen";
htmlres += "" + formatprice(volumentotal, 2) + "";
//htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "
";
htmlres += "" + formatprice(volumentotal * 100 / 20, 1) + " %";
//htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "
";
htmlres += "" + formatprice(volumentotal * 100 / 40, 1) + " %";
//htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "
";
htmlres += "" + formatprice(volumentotal * 100 / 80, 1) + " %";
//htmlres += "";
htmlres += "";
*/
htmlres += "";
htmlres += '
' + totaldinero + "
";
htmlres = gettablehead("tablepedido") + htmlres;
htmlres += '
';
htmlres += '
Desbloqueo Pedido Minimo
';
htmlres += '
';
htmlres += 'Contraseña ';
htmlres +=
' ';
htmlres += "
";
htmlres += "
";
htmlres += '
Notas
';
htmlres += '
';
htmlres += 'Nota Pedido ';
htmlres +=
'";
htmlres += "
";
htmlres += '
';
htmlres += 'Nota Interna ';
htmlres +=
'";
htmlres += "
";
htmlres += '
Direcciones
';
htmlres += '
';
adr.forEach(function (k, v) {
htmlres += '
';
htmlres +=
' ';
htmlres += '';
htmlres +=
"" +
k["ali"].substring(1) + (k["ali"].substring(0,1)=='0'?'*':' ') +
" : " +
k["ad"] +
", " +
k["cp"] +
", " +
k["city"] +
", " +
k["pais"] +
" ";
htmlres += " ";
htmlres += "
";
});
htmlres += "
";
htmlres += '
';
htmlres +=
"
";
htmlres +=
"
Enviar Pedido ";
$(".maxmodalbody").html(htmlres);
if (STOCKAGENTE == "1" && localag > 0) {
$.each(itemsheart, function (key, val) {
//console.log(key + " <<>> " + val);
loadlotes(val);
});
}
$("#direccionespedidos div input[type=radio][name=dire]").change(
function () {
validatepedido();
}
);
$("input[name=pedidominimopass]").change(function () {
validatepedido();
});
//$(".action").off("click");
$("#EnvioPedido").click(function () {
if (validatepedido() > 0) {
return;
}
console.log("Envio Pedido");
kdir = -1;
notaped = "-1xx";
notapedint = "-1xx";
if ($("#direccionespedidos div input:checked")) {
kdir = $("#direccionespedidos div input:checked").val();
}
if (kdir == -1) {
return;
}
notaped = $("#notaped").val();
notapedint = $("#notapedint").val();
//alert(notapedint);
//alert(kdir);
if (isEmpty(localpedido["c"])) {
localpedido["c"] = {};
}
newDate = new Date();
curdatetime = newDate.compressdt();
localpedido["c"].np = notaped;
localpedido["c"].npi = notapedint;
localpedido["c"].d = kdir;
localpedido["c"].dt = curdatetime;
localpedido["c"].ag = localag;
localpedido["c"].cl = localcli;
localpedido["c"].clid = cli["id"];
localpedido["c"].cln = cli["nom"];
if (isEmpty(localpedido["c"].ui)) {
localpedido["c"].ui = uuidv4_date();
}
localpedido["c"].custom = {};
$(".customcampfact").each(function (index) {
localpedido["c"].custom[$(this).attr("name")] = $(this).val();
});
SaveLocalStorage();
$("#blanco").show();
purgapedidosa0();
var jqxhr = $.post("newpedido.php", { data: JSON.stringify(localpedido) })
.done(function (data) {
if (data == localpedido["c"].ui) {
DisplayPedidoOK();
} else {
DisplayPedidoKO("ERROR: " + data);
}
})
.fail(function (xhr, status, error) {
DisplayPedidoKO("error: " + xhr.status + "\r\n No se ha podido enviar el pedido, compruebe su conexion a internet");
})
.always(function (data) {});
});
if (typeof CustomFormPedido === "function") {
CustomFormPedido();
} else {
$("#EnvioPedido").show();
}
validatepedido();
} else if (att == "cambiarcliente") {
mostrarclientesagente();
} else if (att == "cobrarcartera"){
if(object.data('ejercicio')!="0"){
botoncobrarcartera=object;
}
else{
botoncobrarcartera=null;
}
$("#modalcobros").modal("show");
$("#fccantidad").val(object.data('importe'));
$("#fcejercicio").val(object.data('ejercicio'));
$("#fcsucursal").val(object.data('sucursal'));
$("#fccartera").val(object.data('cartera'));
$("#fccomentarios").val('');
$("#procesarcobrofin").show();
$("#cobroresult").html('');
} else if (att == "procesarcobrofin"){
$("#cobroresult").html('');
person=$("#fccantidad").val().replace(",", ".");
if(isNumeric(person)){
$("#procesarcobrofin").hide();
$.ajax({
dataType: "json",
url: 'cobros.php?a='+ localag + "&c=" + localcli + "&ej=" + $("#fcejercicio").val() + "&s=" + $("#fcsucursal").val() + "&ctr=" + $("#fccartera").val()+ "&cnt=" + person + "&tc=" + $("#fctipocobro").val()+ "&com=" + utf8_to_b64($("#fccomentarios").val()) ,
headers: {
"X-Myapp-Nonce": tmph,
},
})
.done(function (data) {
if (data["OK"] > 0) {
$("#cobroresult").html('
Cobro Correcto
')
if(!isEmpty(botoncobrarcartera)){
botoncobrarcartera.hide();
}
botoncobrarcartera=null;
}else if (!isEmpty(data["KO"])) {
$("#cobroresult").html('
ERROR:\n ' + data["KO"] + '
')
botoncobrarcartera=null;
} else {
$("#cobroresult").html('
No se ha procesado el Cobro 1
')
botoncobrarcartera=null;
}
})
.fail(function (jqXHR, textStatus, xhr) {
$("#cobroresult").html('
No se ha procesado el Cobro 1
')
botoncobrarcartera=null;
});
}else{
$("#cobroresult").html('
cantidad introducida no valida
')
}
} else if (att == "cobrarcartera2"){
let text;
let person = prompt("Introduzca la cantidad:", object.data('importe'));
if (person == null || person == "") {
if(isNumeric(person)){
$.ajax({
dataType: "json",
url: 'cobros.php?a='+ localag + "&c=" + localcli + "&ej=" + object.data("ejercicio") + "&s=" + object.data("sucursal") + "&ctr=" + object.data("cartera")+ "&cnt=" + person ,
headers: {
"X-Myapp-Nonce": tmph,
},
})
.done(function (data) {
if (data["OK"] > 0) {
alert("Cobro Enviado")
}else if (!isEmpty(data["KO"])) {
alert("ERROR:\n" + data['KO']);
} else {
alert("No se ha procesado el Cobro")
}
})
.fail(function (jqXHR, textStatus, xhr) {
alert("No se ha procesado el Cobro 1")
});
}else{
alert("cantidad introducida no valida");
}
} else {
person=person.replace(",", ".");
if(isNumeric(person)){
$.ajax({
dataType: "json",
url: 'cobros.php?a='+ localag + "&c=" + localcli + "&ej=" + object.data("ejercicio") + "&s=" + object.data("sucursal") + "&ctr=" + object.data("cartera")+ "&cnt=" + person ,
headers: {
"X-Myapp-Nonce": tmph,
},
})
.done(function (data) {
if (data["OK"] > 0) {
alert("Cobro Enviado")
}else if (!isEmpty(data["KO"])) {
alert("ERROR:\n" + data['KO']);
} else {
alert("No se ha procesado el Cobro")
}
})
.fail(function (jqXHR, textStatus, xhr) {
alert("No se ha procesado el Cobro 1")
});
}else{
alert("cantidad introducida no valida");
}
}
} else if (att == "cobros"){
$("#MaxModalTitle").html("Cobros Agente");
$("#MaxModal").attr("data-tipo", "Cobros");
$("#MaxModal").modal("show");
htmlres="";
htmlres="
";
htmlres+='De: ';
htmlres+=" a ";
htmlres+=' ';
htmlres+=' ';
htmlres+="
";
htmlres+="
";
htmlres+="
";
htmlres+="
";
htmlres+="";
htmlres+="
";
$(".maxmodalbody").html(htmlres);
MapeoAcciones();
} else if (att == "cobrosaction"){
fini=($('#cobrosfechaini').val());
ffin=($('#cobrosfechafin').val());
if(fini==''|| ffin=='' )
{
$('#cobrosresult').html('FECHAS INCORRECTAS');
}
else{
$('#cobrosresult').html('............');
tmph = localag + "|" + 0 + "|" + currentswversion + "|" + kcontra;
tmph = utf8_to_b64(tmph);
$.ajax({
dataType: "json",
url: "/lib/cobrado.php?fi=" + fini + "&ff="+ ffin,
headers: {
"X-Myapp-Nonce": tmph,
},
})
.done(function (data) {
if (data["OK"] > 0) {
htmlres="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
$.each(data['sts'], function (key, val) {
console.log(key);
console.log(val);
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
});
htmlres+='
";
htmlres+='FECHA';
htmlres+=" ";
htmlres+='IMPORTE';
htmlres+=" ";
htmlres+= 'TIPO';
htmlres+=" ";
htmlres+= 'CLIENTE';
htmlres+=" ";
htmlres+= 'TITULO';
htmlres+=" ";
htmlres+=val['FECHACOBRO'];
htmlres+=" ";
htmlres+=val['CANTIDAD'];
htmlres+=" ";
htmlres+= val['TIPOCOBRO'];
htmlres+=" ";
htmlres+= val['SUBNOMBRE'];
htmlres+=" ";
htmlres+= val['TITULOCLIENTE'];
htmlres+="
'
htmlres+='
'
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
$.each(data['sum'], function (key, val) {
htmlres+="";
htmlres+="";
htmlres+="";
htmlres+="";
});
htmlres+='
";
htmlres+= 'TIPO';
htmlres+=" ";
htmlres+='IMPORTE';
htmlres+=" ";
htmlres+= val['TIPOCOBRO'];
htmlres+=" ";
htmlres+=val['CANTIDAD'];
htmlres+="
'
$('#cobrosresult').html(htmlres);
request.onsuccess = function () {
};
request.onerror = function () {
console.log("Error", request.error);
console.log("KO 7");
$('#cobrosresult').html("ERROR 7");
};
} else {
console.log("KO 1");
$('#cobrosresult').html("ERROR 1");
}
})
.fail(function (jqXHR, textStatus, xhr) {
console.log("KO 2");
$('#cobrosresult').html("ERROR 2");
});
}
} else {
alert("nose");
alert(att);
}
}
function validatepedido() {
if (parseFloat($("#pricepedido").text()) < parseFloat(cnf["mv"])) {
if ($("#pedidominimopass").val() != cnf["mvd"]) {
$("#errorpedido").html(
"No se llega al pedido minimo de " +
parseFloat(cnf["mv"]) +
"€
Si desea realizar el pedido introduza la clave de desbloqueo"
);
$("#errorpedido").show();
$("#pedidominimodiv").show();
$("#EnvioPedido").hide();
return 1;
}
} else {
$("#pedidominimodiv").hide();
}
if (!$("#direccionespedidos div input:checked").length > 0) {
$("#errorpedido").html("No hay direccion de envio selecionada");
$("#errorpedido").show();
$("#EnvioPedido").hide();
return 1;
}
if (typeof CustomPedidoValidate === "function") {
ret = CustomPedidoValidate();
if (ret != "") {
$("#errorpedido").html(ret);
$("#errorpedido").show();
$("#EnvioPedido").hide();
return 1;
}
}
$("#errorpedido").html("");
$("#errorpedido").hide();
$("#EnvioPedido").show();
return 0;
}
function DisplayPedidoOK() {
transaction = midb.transaction("kpd", "readwrite");
kpds = transaction.objectStore("kpd"); // (2)
request = kpds.delete(localcli); // (3)
request.onsuccess = function () {
transaction = midb.transaction("kpds", "readwrite");
kpdss = transaction.objectStore("kpds"); // (2)
kpdsinsert = { idcli: localcli, json: JSON.stringify(localpedido) };
request = kpdss.put(kpdsinsert); // (3)
request.onsuccess = function () {
localizador = localpedido["c"].ui;
localpedido = {};
drawpedidos();
$("#MaxModal").modal("hide");
$("#pro").hide();
$("#cat").show();
$("#MediumModalTitle").html("Envio Pedido Correcto");
$("#MediumModal").modal("show");
htmlres =
"Su envio con el localizador
" +
localizador +
" se ha realizado correctmente";
$(".mediummodalbody").html(htmlres);
$("#blanco").hide();
};
request.onerror = function () {
console.log("eeeee");
};
};
request.onerror = function () {
console.log("eeeeeee2");
};
}
function DisplayPedidoKO(kerror) {
alert(kerror);
$("#blanco").hide();
}
function getTotalLinea(idp) {
ret = 0;
cant = dimecantidad(idp);
if (cant == 0) {
return 0;
}
return cant * getPrice(idp);
}
function getVolume(idp) {
vo = 0;
if (!isEmpty(aproduct[idp])) {
if (!isEmpty(aproduct[idp]["vo"])) {
vo = aproduct[idp]["vo"];
vo = parseFloat(aproduct[idp]["vo"].replace(",", "."));
}
}
return vo;
}
function getIntProductValue(idp, kvalue) {
val = getProductValue(idp, kvalue);
if (isEmpty(val)) {
val = 0;
} else {
val = parseInt(val);
}
return val;
}
function getFloatProductValue(idp, kvalue) {
val = getProductValue(idp, kvalue);
if (isEmpty(val)) {
val = 0;
} else {
val = parseFloat(val);
}
return val;
}
function getProductValue(idp, kvalue) {
val = null;
if (!isEmpty(aproduct[idp])) {
if (!isEmpty(aproduct[idp][kvalue])) {
val = aproduct[idp][kvalue];
}
}
return val;
}
function gettablehead(kclase) {
htmlreshead =
"";
/*
htmlreshead += "";
htmlreshead += "";
htmlreshead += "";
htmlreshead += "";
htmlreshead += "";
htmlreshead += "";
htmlreshead += "";
htmlreshead += "";
htmlreshead += "";
htmlreshead += "";
*/
return htmlreshead;
}
function productbyref(ref) {
ret = -1;
$.each(aproduct, function (key, val) {
if (val["reference"].toUpperCase() == ref.toUpperCase()) {
ret = val["id"];
}
});
return ret;
}
function buscador(str) {
itemsct = [];
itemscto = [];
str = str.trim();
tofind = [];
if (str.substr(0, 1) == "|") {
tofind.push(str);
} else {
splstr = str.split(" ");
$.each(splstr, function (key, val) {
val2 = val.trim();
if (val2.length > 1) {
tofind.push(val2);
}
});
}
$.each(aproduct, function (key, val) {
itemsct.push(key);
});
$.each(tofind, function (key, str2) {
itemsct2 = [];
$.each(itemsct, function (key, valx) {
val = aproduct[valx];
encontrado = 0;
ct = val["n"].toUpperCase();
if (!isEmpty(val["reference"])) {
ct += val["reference"].toUpperCase();
}
if (!isEmpty(val["tags"])) {
ct += val["tags"].toUpperCase();
}
console.log(ct);
str2 = str2.toUpperCase();
if (!isEmpty(ct) && ct.indexOf(str2) !== -1) {
if (val["ac"] == "1") {
itemsct2.push(valx);
}
}
});
itemsct = [];
itemsct = itemsct2;
});
itemsheart2=ordenarproductos(itemsct);
htmlres = "";
$.each(itemsheart2, function (key, val) {
console.log(key + " <<>> " + val);
htmlres += DrawProductList3(val);
});
htmlres += "
Ref. Titulo Uds. Precio Total
";
htmlres = gettablehead("tablebuscador") + htmlres;
$(".buscamodalbody").html(htmlres);
}
function ordenarproductos(atoorder){
atoordertmp=Array.from(atoorder);
aordertmp=[];
korden=[];
$.each(atoordertmp, function (key, val) {
aordertmp.push(parseInt(aproduct[val]['ot']));
});
indexo1 = Array.from(aordertmp);
indexo1.sort((a, b) => a - b);
$.each(indexo1, function (key, val) {
$.each(aordertmp, function (key2, val2) {
if(val2==val){
val2='XXX';
atoordertmp[key2]='XXX';
korden.push(key2);
return false
}
});
});
retorden=[];
$.each(korden, function (key, val) {
retorden.push(atoorder[val]);
});
return retorden;
}
function buscador_old(str) {
itemsct = [];
$.each(aproduct, function (key, val) {
encontrado = 0;
ct = val["n"].toUpperCase();
str = str.toUpperCase();
if (!isEmpty(ct) && ct.indexOf(str) !== -1) {
if (aproduct[key]["ac"] == "1") {
itemsct.push(key);
}
encontrado = 1;
}
if (encontrado == 0) {
ct = val["reference"].toUpperCase();
if (!isEmpty(ct) && ct.indexOf(str) !== -1) {
if (aproduct[key]["ac"] == "1") {
itemsct.push(key);
}
encontrado = 1;
}
}
if (encontrado == 0 && !isEmpty(val["tags"])) {
ct = val["tags"].toUpperCase();
console.log(ct);
if (!isEmpty(ct) && ct.indexOf(str) !== -1) {
if (aproduct[key]["ac"] == "1") {
itemsct.push(key);
}
}
}
});
itemsheart = [];
itemsheart = itemsct;
htmlres = "";
$.each(itemsheart, function (key, val) {
//console.log(key + " <<>> " + val);
htmlres += DrawProductList3(val);
});
htmlres += "";
htmlres = gettablehead("tablebuscador") + htmlres;
$(".buscamodalbody").html(htmlres);
}
function purgapedidosa0() {
itemsborrar0 = [];
$.each(localpedido["ped"], function (key, val) {
if (val["qt"] == 0) {
itemsborrar0.push(key);
}
});
$.each(itemsborrar0, function (key, val) {
delete localpedido["ped"][val];
});
}
function getlistapedidos() {
itemsct = [];
$.each(aproduct, function (key, val) {
ct = dimecantidad(val["id"]);
if (!isEmpty(ct) && parseInt(ct) > 0) {
itemsct.push(key);
}
});
return itemsct;
}
function getnumpedidos() {
return getlistapedidos().length;
}
function gettotalpedidosk(){
itemsheart = [];
itemsheart = ordenarproductos(getlistapedidos());
totaldinero = 0;
volumentotal = 0;
$.each(itemsheart, function (key, val) {
totaldinero += getTotalLinea(val);
});
return formatprice(totaldinero/1000, 2);
}
function drawpedidos() {
ctxx = getnumpedidos();
if (ctxx > 0) {
k=gettotalpedidosk();
$(".ncart").html(ctxx + "
" + k);
$(".ncart").show();
} else {
$(".ncart").hide();
}
}
function findParentProduct(id) {
parentproducts = [];
fams = [];
val = aproduct[id];
//console.log(val);
if (val["sh"] == "1") {
parentproducts.push(id);
//console.log("Esta en Show");
} else {
//console.log("No Esta en Show");
$.each(rel, function (index, valor) {
//console.log("RR" + index);
$.each(valor, function (index2, valor2) {
//console.log(" -> " + valor);
if (valor2 == id) {
if ( typeof aproduct[index] === 'undefined') {
console.log ("ERROR rel mal " + index);
}
else if (aproduct[index]["sh"] == "1") {
//console.log("Encuentro parent " + index);
parentproducts.push(index);
}
}
});
});
}
if (parentproducts.length == 0) {
//console.log("No encuentro producto parent");
}
tmpfams2 = [];
$.each(parentproducts, function (index, valor) {
tmpval = findFamProduct(valor);
$.each(tmpval, function (indexx, valorx) {
//console.log(typeof tmpfams[valorx[0]]);
if (typeof tmpfams2[valorx[0]] !== "undefined") {
// your code here
//console.log("mal" + valorx[0]);
} else {
//console.log("anado" + valorx[0]);
tmpfams2[valorx[0]] = valorx;
}
});
//tmpfams2.push(findFamProduct(valor));
});
tmpfams3 = [];
$.each(tmpfams2, function (index, valor) {
if (typeof valor !== "undefined") {
tmpfams3.push(valor);
}
});
//console.log("voy1");
//console.log(parentproducts);
//console.log(tmpfams3);
return tmpfams3;
}
function findFamProduct(id) {
tmpfams = [];
$.each(apo, function (index, valor) {
$.each(valor, function (index2, valor2) {
//console.log(valor2);
if (valor2 == id) {
tmpfams.push([index, afam[index]["n"], id]);
}
});
});
//console.log("Familias de " + id);
//console.log(tmpfams);
return tmpfams;
}
function DrawProductList(id) {
val = aproduct[id];
htmlres = "";
htmlres += "
";
htmlres +=
'
';
htmlres += '
';
htmlres += '
';
htmlres += " ref:" + val["reference"] + " ";
htmlres += "
";
htmlres += '
';
htmlres += " " + val["n"] + "";
htmlres += "
";
htmlres += '
';
htmlres += " " + getFormatPrice(val["id"], 2) + "€";
htmlres += "
";
htmlres += "
";
htmlres += '
';
htmlres +=
'
';
htmlres += "
";
htmlres += '
';
htmlres += '
';
htmlres +=
'
';
htmlres +=
'
';
htmlres +=
'
' +
dimecantidad(id) +
"
";
htmlres +=
'
' +
formatprice(dimecantidad(id) * val["p"], 2) +
" €" +
"
";
tmpparent = findParentProduct(id);
htmlres += '
';
if (tmpparent.length == 0) {
htmlres +=
' Sin Inicio ';
} else {
$.each(tmpparent, function (key, val) {
if (typeof val !== "undefined") {
htmlres +=
' Ir a ' +
val[1] +
" ";
}
});
}
htmlres += drawtags(id);
htmlres += "
";
htmlres += "
";
htmlres += "
";
htmlres += "
";
return htmlres;
}
function DrawProductList2(id) {
val = aproduct[id];
htmlres = "";
htmlres += "";
htmlres += ' ';
htmlres +=
'
';
htmlres += " ";
htmlres +=
'
';
htmlres +=
' ';
htmlres +=
" " + val["reference"] + '
';
htmlres += " ";
htmlres += ' ';
htmlres += " " + val["n"] + "";
htmlres += " ";
htmlres +=
' ' +
formatprice(dimecantidad(id), 0) +
"";
if (STOCKAGENTE == "1" && localag > 0) {
htmlres +=
' ' +
'
x ' +
"";
}
htmlres += ' ';
htmlres += " " + getFormatPrice(val["id"], 2);
htmlres += " ";
htmlres +=
' ' +
formatprice(dimecantidad(id) * val["p"], 2) +
"";
htmlres += ' ';
htmlres += '
';
htmlres +=
'
';
htmlres +=
'
';
htmlres += "
";
htmlres += " ";
htmlres += "";
return htmlres;
}
function DrawProductList3(id) {
val = aproduct[id];
htmlres = "";
htmlres += "";
htmlres += ' ';
htmlres +=
'
';
htmlres += " ";
htmlres +=
'
';
htmlres += ' ';
htmlres += " " + val["n"] + "";
htmlres += " ";
htmlres += ' ';
htmlres +=
'
' +
formatprice(dimecantidad(id), 0) +
"
";
htmlres += '
';
htmlres +=
'
';
htmlres +=
'
';
htmlres += "
";
htmlres += " ";
htmlres += "";
htmlres += "";
htmlres += ' ';
htmlres += " " + val["reference"];
htmlres += " ";
htmlres += ' ';
htmlres += " " + getFormatPrice(val["id"], 2);
htmlres += " ";
htmlres +=
' ' +
formatprice(dimecantidad(id) * val["p"], 2) +
"";
htmlres += "";
htmlres += "";
htmlres += ' ';
tmpparent = findParentProduct(id);
htmlres += '
';
if (tmpparent.length == 0) {
htmlres +=
' Sin Inicio ';
} else {
$.each(tmpparent, function (key, val) {
if (typeof val !== "undefined") {
htmlres +=
' Ir a ' +
val[1] +
" ";
}
});
}
htmlres += drawtags(val["tags"]);
htmlres += "
";
htmlres += " ";
htmlres += "";
return htmlres;
}
function featureformat(kfea) {
retfea="";
try {
retfea=trimChar(kfea.trim(), "|").replaceAll("||", " | ");
}
catch (e) {
retfea="ERROR:" + kfea;
}
return retfea;
}
function drawfams(famid) {
$(".namefamilia").hide();
//$('.paginascount').hide();
resfin = "";
afamorder = [];
var count = 0;
var countt = "";
varcountf = "";
$.each(afam, function (key, val) {
if (val["p2"] == famid) {
afamorder[val["p"]] = key;
}
});
resfin = "
";
//$.each(afamorder, function (index, valor) {
for (var index in afamorder) {
count++;
countt = "F";
countf = afamorder[index];
res = "";
res +=
'
';
res += '
';
//res += ' '
res +=
'
';
res += '
';
res +=
'
' +
afam[afamorder[index]]["n"] +
"
";
res += "
";
/*
res += '
';
res += '
';
res += '
' + afam[afamorder[index]]['n'] + ' ';
res += ' ';
res += '
';
*/
res += "
";
res += "
";
resfin += res;
}
resfin += "
";
resfin += "
";
res = "";
resfin += "
";
ashowproducts = [];
$.each(apo[famid], function (key, val) {
if (aproduct[val] != null) {
if (aproduct[val]["sh"] == "1") {
count++;
countf = famid;
countt = "P";
countp = val;
//console.log(aproduct[val]);
FEA_TIPO = "";
FEA_TIPO2 = "";
FEA_COLOR = "";
if (aproduct[val]["fea"] != null) {
if (KFEA_TIPO != "" && aproduct[val]["fea"][KFEA_TIPO] != null) {
FEA_TIPO = featureformat(aproduct[val]["fea"][KFEA_TIPO]);
}
if (KFEA_TIPO2 != "" && aproduct[val]["fea"][KFEA_TIPO2] != null) {
FEA_TIPO2 = featureformat(aproduct[val]["fea"][KFEA_TIPO2]);
}
if (KFEA_TIPO2 != "" && aproduct[val]["fea"][KFEA_COLOR] != null) {
FEA_COLOR = aproduct[val]["fea"][KFEA_COLOR];
}
}
res = "";
res +=
'
';
res += '
';
res +=
'
';
res += '
';
if (FEA_COLOR != "") {
res += " " + drawcolors(FEA_COLOR);
}
res += "
";
if(INICIOREFERENCIA=='1'){
res += '
';
res +=
'
' + aproduct[val]["reference"] + "
";
res += "
";
}
res += '
';
res +=
'
' + FEA_TIPO2 + "
";
res += "
";
res += '
';
res +=
'
' + FEA_TIPO + "
";
res += "
";
/*
res += '
';
res += '
';
res += '
' + afam[afamorder[index]]['n'] + ' ';
res += ' ';
res += '
';
*/
res += "
";
res += "
";
resfin += res;
} else {
//console.log(key + "->" + aproduct[val]["ac"]);
}
}
//
});
resfin += "
";
if (count == 1 && cnf["sm1"] == 1) {
if (countt == "F") {
drawfams(countf);
} else if (countt == "P") {
gotoproduct(countf, countp, countp);
}
} else {
titulo = getfamiliassub(famid);
//$('.rowfams').html(resfin);
$(".rowfams").html("");
$("#OptionModalBody").html(resfin);
$("#OptionModalTitle").html(titulo);
$("#OptionModal").modal("show");
MapeoAcciones();
}
//drawfams2();
}
function gettitulofam(famid) {
if (famid == -1) {
return "INICIO";
} else {
return afam[famid]["n"];
}
}
function getfamiliassub(famid) {
res = "";
while (famid != -1) {
res =
" |
" +
gettitulofam(famid) +
" " +
res;
famid = afam[famid]["p2"];
}
res =
"
" +
gettitulofam(famid) +
" " +
res;
return res;
}
function drawfams2() {
alert("gato2");
resfin = "";
afamorder = [];
$.each(afam, function (key, val) {
afamorder[val["p"]] = key;
});
//$.each(afamorder, function (index, valor) {
resfin += '
';
for (var index in afamorder) {
res = "";
res += '';
res +=
' ';
res +=
' ';
res += " " + afam[afamorder[index]]["n"];
res += " ";
res += " ";
res += "";
resfin += res;
}
resfin += " ";
$("#OptionModalBody").html(resfin);
$("#OptionModalTitle").html("Familias");
$("#OptionModal").modal("show");
MapeoAcciones();
}
function listsumapro(id, mult) {
event.stopPropagation();
val = aproduct[id];
unidadminimaventa = 9999;
unidadminimaventaindex = -99;
for (i = 1; i <= 6; i++) {
if (
parseInt(val["u" + i]) > 0 &&
parseInt(val["u" + i]) < unidadminimaventa
) {
unidadminimaventa = parseInt(val["u" + i]);
unidadminimaventaindex = i;
}
}
cantidad = unidadminimaventa * mult;
SumaProducto(id, cantidad);
listrenderkcantidadvalue(id);
}
function listrenderkcantidadvalue(idp) {
ori = dimecantidad(idp);
$('div.plist[data-id="' + idp + '"]')
.find("div.listUnidades")
.html(formatprice(ori, 0));
$('tr[data-id="' + idp + '"]')
.find("td.tdlistUnidades")
.html(formatprice(ori, 0));
$('tr[data-id="' + idp + '"] td.tdlistped')
.find("div.tdlistUnidades")
.html(formatprice(ori, 0));
totalprice = formatprice(dimecantidad(idp) * aproduct[idp]["p"], 2);
$('div.plist[data-id="' + idp + '"]')
.find("div.listtotalprice")
.html(totalprice + " €");
$('tr[data-id="' + idp + '"]')
.find("td.tdlisttotalprice")
.html(totalprice);
}
function gotoproduct(dfamilia, dproducto, dsubproducto) {
$("#MaxModal").modal("hide");
$("#BuscaModal").modal("hide");
$("#OptionModal").modal("hide");
val = aproduct[dproducto];
drawproductsfam(dfamilia, 0, dproducto, dsubproducto);
}
function gotoproductobyid(idp) {
$("#MediumModal").modal("hide");
atmp = findParentProduct(idp);
if (atmp.length == 1) {
gotoproduct(atmp[0][0], atmp[0][2], idp);
} else if (atmp.length == 0) {
htmlres = "";
$("#OModalTitle").html("ERROR");
$("#OptionModal").modal("show");
htmlres = "
Este producto no tiene punto de inicio ";
$(".optionmodalbody").html(htmlres);
} else {
htmlres = "";
$("#OptionModalTitle").html("Opciones");
$("#OptionModal").modal("show");
$.each(atmp, function (key, val) {
if (typeof val !== "undefined") {
htmlres +=
'
Ir a ' +
val[1] +
"
";
}
});
$(".optionmodalbody").html(htmlres);
}
}
function drawproductsfam(famid, pos, idp, subproducto) {
$("#cat").hide();
$("#pro").show();
procurrent = 1;
$(".rowpro").html("");
//$('.namefamilia').show();
$(".paginascount").show();
$(".namefamiliatext").html(afam[famid]["n"]);
$(".namefamiliaid").html(famid);
count = 0;
if (isEmpty(pos)) {
pos = 0;
}
if (isEmpty(idp)) {
idp = -1;
}
ashowproducts_full = [];
$.each(apo[famid], function (key, val) {
if (aproduct[val] != null) {
if (aproduct[val]["sh"] == "1") {
//console.log(aproduct[val]);
if (idp != -1 && pos == 0) {
if (aproduct[val]["id"] == idp) {
pos = count;
procurrent = pos + 1;
}
}
count++;
ashowproducts_full.push(val);
} else {
//console.log(key + "->" + aproduct[val]["ac"]);
}
}
//
});
drawproductsarray(pos, pos + propagination);
if (typeof subproducto !== "undefined") {
//console.log("subproducto" + subproducto + " - " + idp);
//console.log($('.imgrelacionado[data-id="' + subproducto + '"]'));
$('.imgrelacionado[data-id="' + subproducto + '"]').trigger("click");
}
}
function drawproductsfamlist(famid) {
$("#cat").hide();
$("#pro").hide();
$("#prolist").show();
procurrent = 1;
$(".rowpro").html("");
//$('.namefamilia').show();
$(".paginascount").show();
$(".namefamiliatext").html(afam[famid]["n"]);
$(".namefamiliaid").html(famid);
count = 0;
$(".rowprolist").html("");
res = "";
ashowproducts = [];
$.each(apo[famid], function (key, val) {
if (aproduct[val] != null) {
if (aproduct[val]["sh"] == "1") {
//console.log(aproduct[val]);
res = "";
res += '
';
res += '
';
res += drawproductolist(aproduct[val]);
res += "
";
res += "
";
$(".rowprolist").append(res);
count++;
} else {
//console.log(key + "->" + aproduct[val]["ac"]);
}
}
//
});
setTimeout(function () {
$(".asyncload").each(function (index) {
//console.log( index + ": " + $( this ).attr("dms-src") );
$(this).attr("src", $(this).attr("dms-src"));
});
//$(".pplus").popover();
$(".pplus").bind("taphold", function () {
res = "";
val = aproduct[$(this).attr("dms-idp")];
res += '
';
res +=
'
' +
unidadesventa[0] +
"
" +
val["u1"] +
'
'+val["unt"]+' ';
res +=
'
' +
unidadesventa[1] +
"
" +
val["u2"] +
'
'+val["unt"]+' ';
res +=
'
' +
unidadesventa[2] +
"
" +
val["u3"] +
'
'+val["unt"]+' ';
res +=
'
' +
unidadesventa[3] +
"
" +
val["u4"] +
'
'+val["unt"]+' ';
res +=
'
' +
unidadesventa[4] +
"
" +
val["u5"] +
'
'+val["unt"]+' ';
res += "
";
$(this).popover({
title: "Unidades Venta",
content: res,
placement: "auto",
html: true,
trigger: "manual",
toggle: "popover",
});
$(this).popover("show");
});
}, 100);
//$('.rowpro').html(res);
}
function drawproductsarray(init, fin) {
if (fin > ashowproducts_full.length) {
fin = ashowproducts_full.length;
}
contadortotal = ashowproducts_full.length;
contadorposicion = init;
drawcontador();
for (var i = init; i < fin; i++) {
renderproductlist(
ashowproducts_full[i],
ashowproducts_full[i + 1],
ashowproducts_full[i - 1]
);
}
}
function openlogistica(id) {
val = aproduct[id];
htmlres = "";
if (STOCKAGENTE == "1" && localag > 0) {
if (!isEmpty(cliagstk[val["reference"]])) {
htmlres += "";
spro = cliagstk[val["reference"]];
$.each(spro, function (key2, val2) {
if (key2 != "t") {
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
}
});
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "
";
} else {
htmlres += "No hay Stock";
}
}
htmlres +=
"
";
htmlres += "";
htmlres +=
"";
if (val["fea"] != null) {
fea = Object.entries(val["fea"]);
fea.forEach(function (k, v) {
fname = k[0];
if (!fname.startsWith("M_IM_")) {
if (fname.startsWith("M_")) {
fname = fname.substring(2);
}
htmlres += "";
htmlres += "";
htmlres += "";
htmlres += "";
}
});
}
htmlres += "
" + "Un." + " " + "Cant." + " " + fname + " " + featureformat(k[1]) + "
";
//$('.modal-body-logistica').html($('.logistica').html());
//$('.modal-body-spincantidad').html($('.spincantidad').html());
$(".modal-body-logistica").html($(".logistica").html() + htmlres);
$("#myModal").modal("show");
$(".modal-body-logistica .kunidad").click(function (event) {
$(".kunidad").removeClass("selected");
at = $(this).attr("data-x");
//$(this).addClass("selected");
$('.kunidad[data-x="' + at + '"]').addClass("selected");
});
$("#notasp" + id).bind("input propertychange", function () {
savenotasproducto($(this).attr("data-id"), this.value);
});
loadlotes(id);
$(".sagc").bind("input propertychange", function () {
changelote(id);
});
}
function changelote(idp) {
if (STOCKAGENTE == "1" && localag > 0) {
console.log("change stock");
total = 0;
txxto = "";
$(".sagc").each(function (index) {
if (parseInt($(this).val()) > 0) {
txxto += $(this).attr("data-lote") + "," + $(this).val() + ";";
}
});
savelotesproducto(idp, txxto);
loadlotes(idp);
}
}
function savelotesproducto(idp, lotes) {
if (STOCKAGENTE == "1" && localag > 0) {
if (isEmpty(localpedido["ped"])) {
localpedido["ped"] = {};
}
if (isEmpty(localpedido["ped"][idp])) {
localpedido["ped"][idp] = {};
}
localpedido["ped"][idp].lt = lotes;
SaveLocalStorage();
}
}
function loadlotes(idp) {
if (STOCKAGENTE == "1" && localag > 0) {
totallotes = 0;
totalpedido = 0;
if (!isEmpty(localpedido) && !isEmpty(localpedido["ped"]) && !isEmpty(localpedido["ped"][idp])) {
if (!isEmpty(localpedido["ped"][idp].qt)) {
totalpedido = parseInt(localpedido["ped"][idp].qt);
}
if (!isEmpty(localpedido["ped"][idp].lt)) {
lotes = localpedido["ped"][idp].lt;
var valores = lotes.split(";");
valores.forEach(function (k, v) {
dos = k.split(",");
if (dos.length == 2) {
$('.sagc[data-lote="' + dos[0] + '"]').val(dos[1]);
totallotes += parseInt(dos[1]);
}
});
}
}
total = totalpedido - totallotes;
$(".lotecount[data-id='" + idp + "']").html(total);
if (total != 0) {
$(".lotecount[data-id='" + idp + "']").show();
} else {
$(".lotecount[data-id='" + idp + "']").hide();
}
}
}
function savenotasproducto(idp, nota) {
if (isEmpty(localpedido["ped"])) {
localpedido["ped"] = {};
}
if (isEmpty(localpedido["ped"][idp])) {
localpedido["ped"][idp] = {};
}
localpedido["ped"][idp].n = nota;
SaveLocalStorage();
}
function SaveLocalStorage() {
purgapedidosa0();
//localStorage.setItem("qt" + localcli, JSON.stringify(localpedido));
transaction = midb.transaction("kpd", "readwrite");
kpds = transaction.objectStore("kpd"); // (2)
kpdinsert = { id: localcli, json: JSON.stringify(localpedido) };
request = kpds.put(kpdinsert); // (3)
request.onsuccess = function () {
//animocorazonfooter();
};
request.onerror = function () {
//animocorazonfooter();
};
}
function getnotasproducto(idp) {
nota = "";
if (!isEmpty(localpedido["ped"])) {
if (!isEmpty(localpedido["ped"][idp])) {
if (!isEmpty(localpedido["ped"][idp].n)) {
nota = localpedido["ped"][idp].n;
}
}
}
return nota;
}
function getnotaPedido() {
nota = "";
if (!isEmpty(localpedido["c"])) {
if (!isEmpty(localpedido["c"].np)) {
nota = localpedido["c"].np;
}
}
return nota;
}
function savenotaPedido(){
if (isEmpty(localpedido["c"])) {
localpedido["c"] = {};
}
localpedido["c"].np=$("#notaped").val();
}
function getnotaPedidoI() {
nota = "";
if (!isEmpty(localpedido["c"])) {
if (!isEmpty(localpedido["c"].npi)) {
nota = localpedido["c"].npi;
}
}
return nota;
}
function savenotaPedidoI(){
if (isEmpty(localpedido["c"])) {
localpedido["c"] = {};
}
localpedido["c"].npi=$("#notapedint").val();
}
function purgadatos() {
familiashuerfanas();
productossinfamilia();
}
function famfilter() {
tarifa = cli["gro"];
tarifa = parseInt(tarifa) - 10;
tmpa = [];
$.each(afam, function (key, val) {
ft = val["ft"];
if (ft.length > 0 && ft.substring(0, 1) == "-") {
ft = "," + ft.substring(1) + ",";
if (ft.search("," + tarifa + ",") >= 0) {
tmpa.push(key);
}
}
});
if (tmpa.length > 0) {
$.each(tmpa, function (key, val) {
deletefamilia(val);
});
}
}
function deletefamilia(id) {
delete afam["" + id + ""];
delete apo["" + id + ""];
}
function familiashuerfanas() {
tmpa = [];
tmpa2 = [];
tmpa.push("-1");
$.each(afam, function (key, val) {
tmpa.push(key);
});
console.log(tmpa);
$.each(afam, function (key, val) {
if (!tmpa.includes(val["p2"])) {
tmpa2.push(key);
}
});
console.log(tmpa2);
if (tmpa2.length > 0) {
$.each(tmpa2, function (key, val) {
deletefamilia(val);
});
familiashuerfanas();
}
}
function productossinfamilia() {
tmpa = [];
$.each(aproduct, function (key, val) {
tmpa.push(key);
});
$.each(apo, function (key, val) {
//tmpa.push(key);
console.log("fam" + key);
$.each(val, function (key2, val2) {
//tmpa.push(key);
//console.log("p" + key2 + " " + val2);
var index = tmpa.indexOf(val2);
if (index !== -1) {
tmpa.splice(index, 1);
}
});
});
console.log("Sin Familia");
console.log(tmpa);
console.log("END Familia");
$.each(tmpa, function (key, val) {
delete aproduct[val];
});
console.log("end purga");
}
function displayconsumos(obj) {
art = obj.attr("data-id");
htmlres = "";
htmlres += "";
alb.forEach(function (k, v) {
if (k["a"] == art) {
htmlres +=
"";
}
});
htmlres += "
Fecha Dir. Cant. Alb. " +
k["f"] +
" " +
k["e"] +
"* " +
k["c"] +
" " +
k["al"] +
"
";
htmlres += "
";
htmlres += "
";
htmlres += GetDirecciones();
$("#MediumModalTitle").html("Consumos [" + art + "]");
$("#MediumModal").modal("show");
$(".mediummodalbody").html(htmlres);
}
function GetDirecciones() {
htmlres = "";
adr.forEach(function (k, v) {
htmlres +=
"
" +
k["ali"].substring(1) +
"* :
" +
k["ad"] +
", " +
k["cp"] +
", " +
k["city"] +
", " +
k["pais"] +
" ";
});
return htmlres;
}
function displayalbaran(idalbaran) {
htmlres = "";
//htmlres += "";
alb.forEach(function (k, v) {
if (k["al"] == idalbaran) {
namep = "nose";
if (!isEmpty(pref[k["a"]])) {
idp = pref[k["a"]];
if (!isEmpty(aproduct[idp])) {
namep = aproduct[idp]["n"];
imgsrc = getpimg(aproduct[idp]["im"]);
}
}
if (namep != "nose") {
cantidadp = dimecantidad(idp);
cantidadp = cantidadp == 0 ? "" : cantidadp;
htmlres +=
"";
}
}
});
htmlres += "
Cod. prod Cant. " +
k["a"] +
" " +
namep +
" " +
k["c"] +
" " +
cantidadp +
"
";
ct = getnumpedidos();
if (ct == 0) {
htmlres +=
'
" +
"Copiar Pedido desde albaran" +
" ";
}
$("#MediumModalTitle").html("Albaran [" + idalbaran + "]");
$("#MediumModal").modal("show");
$(".mediummodalbody").html(htmlres);
}
function drawproductlistmosaic(val) {
res = "";
res += "gato";
return res;
}
function drawproductolist(val) {
res = "";
res += '
';
res +=
'
';
res += "
";
res += '
';
res += '
';
res +=
' ' + val["reference"] + " ";
res +=
' ' +
getFormatPrice(val["id"], 2) +
" € ";
res += "
";
kcant = dimecantidad(val["id"]);
kcantclass = "";
if (kcant == 0) {
kcantclass = "hidezero";
}
res +=
'
';
res +=
'
' +
val["u1"] +
"
";
res +=
'
' +
formatprice(kcant, 0) +
"
";
res +=
'
";
res +=
'
";
res += "
";
res += "
";
return res;
}
function drawtags(valor) {
res = "";
if (isEmpty(valor)) {
return res;
}
var valores = valor.split("||");
valores.forEach(function (k, v) {
tag = k
.replace("|", "")
.replace("|", "")
.replace("|", "")
.replace("|", "")
.replace("|", "");
res +=
'
" +
tag +
" ";
});
return res;
}
function drawcolors(valor) {
res = "
";
if (isEmpty(valor)) {
res += "
";
return res;
}
var valores = valor.split("||");
valores.forEach(function (k, v) {
tag = k
.replace("|", "")
.replace("|", "")
.replace("|", "")
.replace("|", "")
.replace("|", "");
res += "
";
});
res += "
";
return res;
}
function drawproducto(val) {
res = "";
res += ' ';
res +=
'
';
res += " " + $(".namefamiliatext").text();
res += "
";
res += '
';
res += drawtags(val["tags"]);
res += "
";
res += "
";
res += '
';
res += ' ';
//res += '
';
res +=
'
';
res +=
'
49
';
//res += '
+ Colors
';
res += "
";
res += ' ';
res +=
'
' +
getFormatPrice(val["id"], 2) +
" €
";
res +=
'
';
res +=
' ';
res +=
' ';
res += " ";
res += '
';
res += " Ref:" + val["reference"] + " ";
res += " " + drawtags(val["tags"]) + "";
res += "
";
/*
res += '
';
res += '
' + val['n'] + '
';
res += '
';
*/
res += "
";
//res += '
';
if (val["nw"] == 1 /*&& val['fid'] != 10*/) {
res += '
';
}
if (val["lq"] == 1) {
res += '
';
} else if (val["lq"] == 2) {
res += '
';
} else if (val["lq"] == 3) {
res += '
';
} else if (val["lq"] == 4) {
res += '
';
} else if (val["lq"] == 5) {
res += '
';
} else if (val["lq"] == 6) {
res += '
';
}
res += "
";
res += "
";
res += ' ';
res += '
';
res += '
';
res += '
';
res += " " + val["reference"] + "";
res += "
";
res += '
' + val["n"] + "
";
res += "
";
res += "
";
res += '
';
unidadminimaventa = 9999;
unidadminimaventaindex = -99;
counttiposunidades = 0;
for (i = 1; i <= 6; i++) {
counttiposunidades += val["u" + i] > 0 ? 1 : 0;
if (
parseInt(val["u" + i]) > 0 &&
parseInt(val["u" + i]) < unidadminimaventa
) {
unidadminimaventa = parseInt(val["u" + i]);
unidadminimaventaindex = i;
}
}
unidaddefecto=unidadminimaventaindex;
if(unidadesventadefecto>unidaddefecto){
if(val["u" + unidaddefecto]>0){
unidaddefecto=unidadesventadefecto;
}
}
if (counttiposunidades == 1 && cnf["ouv"] == 1) {
res += '
';
} else {
res += '
';
}
for (i = 1; i <= 6; i++) {
res +=
'
' +
unidadesventa[i - 1] +
"
" +
val["u" + i] +
'
'+val["unt"]+' ';
}
res += "
";
res += '
";
//res += '
' + val['u6'] + '
';
res += '
';
res += "
";
res += '
';
res += "
";
res += '
';
return res;
}
function getclassstock(idproduct){
var retstopclas="";
var stoc=parseInt(aproduct[idproduct]['sto']);
if(stoc
48
46
';
$.each(rel[id], function (key, val) {
//console.log("rel:" + val);
rp = aproduct[val];
if (rp != null) {
rimg = rp["im"];
rimgurl = getpimg(rimg);
if (val == id) {
//no dibujo el mismo porque ya lo he dibujado antes
//res += ' 48
46
';
} else {
res +=
' 47
45
';
}
}
});
res += '
';
res += " ";
res += "
";
if (!isEmpty(next)) {
res +=
'
';
}
if (!isEmpty(prev)) {
res +=
'
';
}
//$('.rowpro').append(res);
$(".rowpro").html(res);
setTimeout(function () {
//console.log($("#relacionados").innerHeight() + " -> " + $("#relacionados").height() + " -> " + $("#relacionados").outerHeight() + " -> " + ($("#relacionados")).prop('scrollHeight'));
if (
$("#relacionados").innerHeight() < $("#relacionados").prop("scrollHeight")
) {
$(".flecharelacionados").show();
}
}, 400);
drawconsumos();
$(".imgrelacionado").click(function () {
//console.log($(this));
renderonlyproductlist($(this).attr("data-id"));
});
$("#relacionados").scroll(function () {
$(".flecharelacionados").hide();
});
$(".imgplist").click(function (event) {
showgallery($(this));
});
$(".kunidad").click(function (event) {
$(".kunidad").removeClass("selected");
at = $(this).attr("data-x");
//$(this).addClass("selected");
$('.kunidad[data-x="' + at + '"]').addClass("selected");
});
$(".corazon").click(function (event) {
idp = $(this).attr("data-id");
cz = aproduct[idp]["cz"];
if (isEmpty(cz) || cz == 0) {
aproduct[idp]["cz"] = 1;
$(".corazonvacio").hide(100);
$(".corazonlleno").show(200);
} else {
aproduct[idp]["cz"] = 0;
$(".corazonlleno").hide(100);
$(".corazonvacio").show(200);
}
savecorazones();
});
renderkcantidadvalue(id);
/*
$(".imgplist").one("load", function () {
////console.log("uno")
}).each(function () {
if (this.complete) {
$(this).load(); // For jQuery < 3.0
// $(this).trigger('load'); // For jQuery >= 3.0
//console.log("dos");
}
});
*/
cz = val["cz"];
if (!isEmpty(cz) && cz == 1) {
$(".corazonvacio").hide();
$(".corazonlleno").show();
}
MapeoAcciones();
clearTimeout(loadlotes);
timeoutloadlotes = setTimeout(function () {
loadlotes(id);
}, 50);
}
function borrarcorazonestodos() {
$.each(aproduct, function (key, val) {
heart = val["cz"];
if (heart == 1) {
val["cz"] = 0;
}
});
cuantoscorazones = 0;
animocorazonfooter();
transaction = midb.transaction("khe", "readwrite");
khes = transaction.objectStore("khe");
request = khes.delete(localcli);
request.onerror = function () {};
request.onsuccess = function () {};
$("#MaxModal").modal("hide");
}
function borrarcorazon(idp) {
aproduct[idp]["cz"] = 0;
savecorazones();
}
function listborrar(kitem) {
//kitem.parent().parent().html() esto es el tr hay que eliminarlo
//kitem.data("id") id producto para eliminar
//kitem.parent().parent().parent().parent().hasClass('tableheart') si es un borrado de corazon
if (kitem.parent().parent().parent().parent().hasClass("tableheart")) {
idp = kitem.data("id");
borrarcorazon(idp);
kitem.parent().parent().remove();
}
console.log(kitem);
}
function loadcorazones() {
cuantoscorazones = 0;
transaction = midb.transaction("khe");
khes = transaction.objectStore("khe");
request = khes.get(localcli);
request.onerror = function () {
console.error("Error", request.error);
};
request.onsuccess = function () {
gatorrrr = request.result;
if (!isEmpty(gatorrrr)) {
data = gatorrrr["json"];
itemsheart = JSON.parse(data);
$.each(aproduct, function (key, val) {
if (itemsheart.includes(key)) {
val["cz"] = 1;
cuantoscorazones++;
}
});
if (cuantoscorazones > 0) {
animocorazonfooter();
}
} else {
}
// continúa trabajando con la base de datos usando el objeto db
};
}
function savecorazones() {
itemsheart = [];
$.each(aproduct, function (key, val) {
heart = val["cz"];
if (heart == 1) {
itemsheart.push(key);
}
});
cuantoscorazones = itemsheart.length;
transaction = midb.transaction("khe", "readwrite");
khes = transaction.objectStore("khe"); // (2)
kheinsert = { id: localcli, json: JSON.stringify(itemsheart) };
request = khes.put(kheinsert); // (3)
request.onsuccess = function () {
animocorazonfooter();
};
request.onerror = function () {
animocorazonfooter();
};
}
function animocorazonfooter() {
$(".corazonllenofooter").show();
setTimeout(function () {
$(".corazonllenofooter").hide();
}, 3000);
$(".ncorazones").html(cuantoscorazones);
if (cuantoscorazones > 0) {
$(".ncorazones").show();
} else {
$(".ncorazones").hide();
}
}
function renderonlyproductlist(id) {
//console.log(id);
val = aproduct[id];
console.log(val);
res = "";
res += drawproducto(val);
$(".imgprocol").html(res);
drawconsumos();
$(".imgrelacionado").each(function () {
if ($(this).attr("data-id") == id) {
$(this).parent().addClass("current");
} else {
$(this).parent().removeClass("current");
}
});
$(".imgplist").click(function (event) {
showgallery($(this));
});
$(".kunidad").click(function (event) {
$(".kunidad").removeClass("selected");
$(this).addClass("selected");
});
$(".corazon").click(function (event) {
idp = $(this).attr("data-id");
cz = aproduct[idp]["cz"];
if (isEmpty(cz) || cz == 0) {
aproduct[idp]["cz"] = 1;
$(".corazonvacio").hide(100);
$(".corazonlleno").show(200);
} else {
aproduct[idp]["cz"] = 0;
$(".corazonlleno").hide(100);
$(".corazonvacio").show(200);
}
savecorazones();
});
cz = val["cz"];
if (!isEmpty(cz) && cz == 1) {
$(".corazonvacio").hide();
$(".corazonlleno").show();
}
renderkcantidadvalue(id);
MapeoAcciones();
}
function getpimg(id) {
//return "./img/noimage.gif";
if (isEmpty(id)) {
return "./img/offline.jpg";
} else {
if (online == 0) {
return "http://127.0.0.1:7777/p/" + id + prosuf;
} else {
fin = "";
idx = id + "";
var i = 0;
for (i = 0; i < idx.length; i++) {
fin += idx.substring(i, i + 1) + "/";
}
fin += id + prosuf;
fin = propath + fin;
return fin;
}
}
}
function getimg(id) {
//return "./img/noimage.gif";
if (isEmpty(id)) {
return "./img/noimage.gif";
} else {
if (online == 0) {
return "http://127.0.0.1:7777/s/" + id;
} else {
fin = "";
fin = imgpath + fin + id;
return fin;
}
}
}
function getcimg(id) {
if (isEmpty(id)) {
return "./img/noimage.gif";
} else {
if (online == 0) {
return "http://127.0.0.1:7777/c/" + id + famsuf;
} else {
fin = "";
fin += id + famsuf;
fin = fampath + fin;
return fin;
}
}
}
function gototag(ktag) {
ktag = "|" + ktag + "|";
$("#BuscaModal").modal("show");
$("#kbusco").val(ktag);
buscador(ktag);
}
function PlaySound() {
//var sound = document.getElementById("audio");
//sound.play()
soundEffect.play();
}
function getPrice(id) {
retprecio = aproduct[id]["p"];
return parseFloat(retprecio);
}
function getFormatPrice(id, decimales) {
retprecio = aproduct[id]["p"];
return formatprice(retprecio, decimales);
}
function numberWithCommas(x) {
var parts = x.toString().split(",");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
return parts.join(".");
}
function formatprice(price, decimales) {
if (price == undefined) {
return "-";
}
price = parseFloat(price.toString().replace(",", ".")).toFixed(decimales);
ResultStr = price.toString();
if (ResultStr != null) {
var SplitChars = ".";
if (ResultStr.indexOf(SplitChars) >= 0) {
var DtlStr = ResultStr.split(SplitChars);
decimaless = "";
if (decimales > 0) {
decimaless = ',
' + DtlStr[1] + " ";
}
return numberWithCommas(DtlStr[0]) + decimaless;
//return 'gato';
} else {
return numberWithCommas(price);
}
}
}
function dimecantidad(idp) {
ori = 0;
if (!isEmpty(localpedido["ped"])) {
if (!isEmpty(localpedido["ped"][idp])) {
if (!isEmpty(localpedido["ped"][idp].qt)) {
ori = localpedido["ped"][idp].qt;
}
}
}
if (isEmpty(ori)) {
ori = 0;
}
return ori;
}
function masproducto(idp, mult, eslista = 0) {
if (eslista == 1) {
cuantos =
parseInt($("#prolist .kunidadlist" + idp).html()) * parseInt(mult);
} else {
cuantos =
parseInt($("#pro .kunidad.selected").attr("data-c")) * parseInt(mult);
}
//alert(cuantos);
SumaProducto(idp, cuantos);
renderkcantidadvalue(idp);
}
function recuperarpedidodesdealbaran(ida){
alb.forEach(function (k, v) {
if (k["al"] == ida) {
idp = pref[k["a"]];
SumaProducto(idp,k["c"]);
}
$('.modal').modal("hide");
$('#idbuttonpedido').click()
});
}
function SumaProducto(idp, suma) {
ori = dimecantidad(idp);
suma=parseInt(suma);
tmpqt = ori + suma;
if (tmpqt < 0) {
tmpqt = 0;
}
if (tmpqt != ori) {
if (isEmpty(localpedido["ped"])) {
localpedido["ped"] = {};
}
if (isEmpty(localpedido["ped"][idp])) {
localpedido["ped"][idp] = {};
}
localpedido["ped"][idp].qt = tmpqt;
localpedido["ped"][idp].pri = aproduct[idp]["p"];
loadlotes(idp);
SaveLocalStorage();
PlaySound();
}
clearTimeout(drawpedidostimer);
drawpedidostimer = setTimeout(drawpedidos, 1000);
if ($("#dineropedidototal").is(":visible")) {
itemsheart = [];
itemsheart = ordenarproductos(getlistapedidos());
totaldinero = 0;
volumentotal = 0;
unidadestotal=0;
$.each(itemsheart, function (key, val) {
totaldinero += getTotalLinea(val);
unidadestotal+=dimecantidad(val);
volumentotal +=
(getVolume(val) * dimecantidad(val)) / getFloatProductValue(val, "u5");
});
$("#dineropedidototal").html(formatprice(totaldinero, 2));
$("#pricepedido").html(totaldinero);
$("#unidadespedidototal").html(unidadestotal);
validatepedido();
}
}
function renderkcantidadvalue(idp) {
ori = dimecantidad(idp);
if (ori == 0) {
$(".spincantidadlist" + idp).addClass("hidezero");
} else {
$(".spincantidadlist" + idp).removeClass("hidezero");
}
$(".kcantidadlist" + idp).html(formatprice(ori, 0)) ;
$(".kcantidadvalue").html(formatprice(ori, 0) + '
'+val["unt"]+' ');
unidadminimaventa = 9999;
unidadminimaventaindex = -99;
for (i = 1; i <= 6; i++) {
if (
parseInt(val["u" + i]) > 0 &&
parseInt(val["u" + i]) < unidadminimaventa
) {
unidadminimaventa = parseInt(val["u" + i]);
unidadminimaventaindex = i;
}
//console.log("unidad venta" + i + "->" + val["u" + i]);
}
textunidades='';
P=ori;
for (i = 6; i >= 1; i--) {
if (parseInt(val["u" + i]) > 0) {
Q=parseInt(val["u" + i]);
R1 = Math.floor(P / Q);
if(R1>0){
textunidades+= R1+ unidadesventashort[i - 1] + " ";
P=P % Q;
}
}
}
//console.log(textunidades);
unidades = aproduct[idp]["u" + unidadminimaventaindex];
kunidades = ori / unidades;
/*
$(".unidades").html(
formatprice(kunidades, 0) +
" " +
unidadesventashort[unidadminimaventaindex - 1]
);
*/
$(".unidades").html(textunidades);
drawcantidadpedida();
}
function checkKey(e) {
e = e || window.event;
if (e.keyCode == "38") {
// up arrow
} else if (e.keyCode == "40") {
// down arrow
} else if (e.keyCode == "37") {
moveproduct(-1);
} else if (e.keyCode == "39") {
moveproduct(1);
}
}
function showgallery(obj) {
iszoom = 1;
//$('#bodyzoom2').html(htmlres);
//$('#imgzoom2').attr("src", $(this).attr('data-img'));
//$('#transition2').show();
/*
jsonxx = [{
"src": '../static/img/1.jpg',
'thumb': '../static/img/thumb-1.jpg',
'subHtml': '
Fading Light Classic view from Rigwood Jetty on Coniston Water an old archive shot similar to an old post but a little later on.
'
}, {
'src': '../static/img/2.jpg',
'thumb': '../static/img/thumb-2.jpg',
'subHtml': "
Bowness Bay A beautiful Sunrise this morning taken En-route to Keswick not one as planned but I'm extremely happy I was passing the right place at the right time....
"
}, {
'src': '../static/img/3.jpg',
'thumb': '../static/img/thumb-3.jpg',
'subHtml': "
Coniston Calmness Beautiful morning
"
}];
*/
jsonxx = [];
val = aproduct[obj.attr("data-pid")];
val["img"].forEach(function (k, v) {
jsonxx.push({ src: getpimg(k), thumb: getpimg(k) });
});
//$('#zoomimg2').lightGallery();
obj.lightGallery({
dynamic: true,
share: false,
download: false,
thumbnail: true,
autoplayControls: false,
dynamicEl: jsonxx,
});
obj.on("onCloseAfter.lg", function (event, index, fromTouch, fromThumb) {
iszoom = 0;
});
event.stopPropagation();
/*event.preventDefault();
event.stopImmediatePropagation();
return false;
*/
}
function headercartera(curcartera) {
var htmlres = "";
htmlres +=
'';
if (curcartera == 0) {
htmlres +=
'';
} else if (curcartera == 2) {
htmlres +=
'';
}
/*htmlres += '';*/
htmlres +=
'';
htmlres +=
'';
return htmlres;
}
function footercartera(valor, moneda, curcartera) {
var htmlres = "";
htmlres += '';
/*htmlres += '';
htmlres += '';
htmlres += '';*/
if (curcartera == 0) {
htmlres +=
'";
} else if (curcartera == 2) {
htmlres +=
'";
}
//htmlres += '';
htmlres +=
"";
htmlres += "";
htmlres += "";
/*
if (curcartera == 0 && moneda == '€') {
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
}
else if (curcartera == 0 && moneda == '£') {
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
}
if (curcartera == 2 && moneda == '€') {
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
}
else if (curcartera == 2 && moneda == '£') {
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
htmlres += '';
}
*/
htmlres += "";
htmlres += "
' +
"Empresa " +
curcartera +
' ' +
"Empresa " +
curcartera +
' ' + lan(73) + ' ' + lan(82) + ' ' + lan(103) + ' ' + lan(74) + ' Dto. Esp Dto. Pp ' + lan(76) + ' ' + lan(75) + ' Fecha Recogida ' +
"Fecha" +
" " +
"Vencimiento" +
" " +
"Factura" +
' ' +
"Referencia" +
' ' +
"Importe" +
' ' +
"Total Empresa0" +
" ' +
"Total Empresa2" +
" " +
formatprice(parseFloat(valor), 2) +
" " +
moneda +
" ";
htmlres += "' + 'BBVA, S.A.' + ' ' + 'IBAN: ES75 0182 5465 9102 0153 9033' + ' ' + 'SWIFT CODE: BBVAESMMXXX' + ' ' + 'CAIXABANK, S.A.' + ' ' + 'IBAN: ES28 2100 2834 9002 0009 9017' + ' ' + 'SWIFT CODE: CAIXESBBXXX' + ' ' + 'CAIXABANK, S.A.' + ' ' + 'IBAN: ES88 2100 8604 0772 0030 7287' + ' ' + 'SWIFT CODE: CAIXESBBXXX' + ' ' + 'BBVA, S.A.' + ' ' + 'IBAN: ES27 0182 5465 9802 0153 7808' + ' ' + 'SWIFT CODE: BBVAESMMXXX' + ' ' + 'CAIXABANK, S.A.' + ' ' + 'IBAN: ES35 2100 2834 9702 0009 9130' + ' ' + 'SWIFT CODE: CAIXESBBXXX' + ' ' + 'CAIXABANK, S.A.' + ' ' + 'IBAN: ES54 2100 8604 0272 0030 7174' + ' ' + 'SWIFT CODE: CAIXESBBXXX' + '
";
return htmlres;
}
function localStorageSpace() {
var allStrings = "";
for (var key in window.localStorage) {
if (window.localStorage.hasOwnProperty(key)) {
allStrings += window.localStorage[key];
}
}
return allStrings
? formatprice(3 + (allStrings.length * 16) / (8 * 1024), 2) + " KB"
: "Empty (0 KB)";
}
function testLocalStorage() {
var timeStart = Date.now();
var timeEnd, countKey, countValue, amountLeft, itemLength;
var occupied = (leftCount = 3); //Shurav's comment on initial overhead
//create localStorage entries until localStorage is totally filled and browser issues a warning.
var i = 0;
while (!error) {
try {
//length of the 'value' was picked to be a compromise between speed and accuracy,
// the longer the 'value' the quicker script and result less accurate. This one is around 2Kb
localStorage.setItem(
"testKey" + i,
"11111111112222222222333333333344444444445555555555666661111111111222222222233333333334444444444555555555566666"
);
} catch (e) {
var error = e;
}
i++;
}
//if the warning was issued - localStorage is full.
if (error) {
//iterate through all keys and values to count their length
for (var i = 0; i < localStorage.length; i++) {
countKey = localStorage.key(i);
countValue = localStorage.getItem(localStorage.key(i));
itemLength = countKey.length + countValue.length;
//if the key is one of our 'test' keys count it separately
if (countKey.indexOf("testKey") !== -1) {
leftCount = leftCount + itemLength;
}
//count all keys and their values
occupied = occupied + itemLength;
}
//all keys + values lenght recalculated to Mb
occupied = ((occupied * 16) / (8 * 1024) / 1024).toFixed(2);
//if there are any other keys then our 'testKeys' it will show how much localStorage is left
amountLeft = occupied - ((leftCount * 16) / (8 * 1024) / 1024).toFixed(2);
//iterate through all localStorage keys and remove 'testKeys'
Object.keys(localStorage).forEach(function (key) {
if (key.indexOf("testKey") !== -1) {
localStorage.removeItem(key);
}
});
}
//calculate execution time
var timeEnd = Date.now();
var time = timeEnd - timeStart;
//create message
var message =
"Finished in: " +
time +
"ms \n total localStorage: " +
occupied +
"Mb \n localStorage left: " +
amountLeft +
"Mb";
//put the message on the screen
document.getElementById("testLocalStorage").innerText = message; //this works with Chrome,Safari, Opera, IE
//document.getElementById('scene').textContent = message; //Required for Firefox to show messages
}
//custom file
/*
function CustomPostLoadData(){
$.each(aproduct, function (k, v) {
aproduct[k]["u1"]= 1;
}) ;
}
*/